LeetCode-Recover Binary Search Tree

/**
 * 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;
        }
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章