99.Recover Binary Search Tree

class Solution {
public:
    void recoverTree(TreeNode *root) {
        TreeNode *cur=root,*pre=nullptr;
        TreeNode *first=nullptr,*second=nullptr,*parent=nullptr;
        while(cur)
        {
            if(!cur->left)
            {
                if(parent && parent->val > cur->val)
                {
                    if (!first)
                        first=parent;
                    second=cur;
                }
                parent=cur;
                cur=cur->right;
            }
            else
            {
                pre=cur->left;
                while(pre->right != nullptr && pre->right != cur)
                    pre=pre->right;
                if(pre->right == nullptr)
                {
                    pre->right=cur;
                    cur=cur->left;
                }
                else
                {
                    pre->right=nullptr;
                    if(parent && parent->val > cur->val)
                    {
                        if (!first)
                            first=parent;
                        second=cur;
                    }
                    parent=cur;
                    cur=cur->right;
                }
            }
        }
        if (first && second) swap(first->val, second->val);
    }
};
posted @ 2019-04-09 14:30  JohnRed  阅读(68)  评论(0编辑  收藏  举报