您的位置:首页 > 其它

LeetCode-Recover Binary Search Tree

2013-08-15 16:30 429 查看
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
TreeNode *p = root;
TreeNode *pre = NULL;
TreeNode *first = NULL;
TreeNode *second = NULL;
TreeNode *third = NULL;
TreeNode *fourth = NULL;
stack<TreeNode *> stk;
while (p != NULL || !stk.empty())
{
if (p == NULL)
{
p = stk.top();
stk.pop();
if (pre == NULL)
{
pre = p;
}
else
{
if (pre->val > p->val)
{
if (first == NULL)
{
first = pre;
second = p;
}
else
{
third = pre;
fourth = p;
break;
}
}
pre = p;
p = p->right;
}
}
else
{
stk.push(p);
p = p->left;
}
}
if (third == NULL)
{
int tmp = first->val;
first->val = second->val;
second->val = tmp;
}
else
{
int tmp = first->val;
first->val = fourth->val;
fourth->val = tmp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: