99. Recover Binary Search Tree -- 找到二叉排序树中交换过位置的两个节点

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void recoverTree(TreeNode* root) {
        stack s;
        TreeNode *p = root, *last = NULL, *p1 = NULL, *p2 = NULL;
        while(p || !s.empty())
        {
            while(p)
            {
                s.push(p);
                p = p->left;
            }
            if(!s.empty())
            {
                p = s.top();
                s.pop();
                if(last && last->val >= p->val)
                {
                    p2 = p;
                    if(!p1)
                        p1 = last;
                    else
                        break;
                }
                last = p;
                p = p->right;
            }
        }
        swap(p1->val, p2->val);
    }
};

 

转载于:https://www.cnblogs.com/argenbarbie/p/5411678.html

你可能感兴趣的:(99. Recover Binary Search Tree -- 找到二叉排序树中交换过位置的两个节点)