LeetCode: Recover Binary Search Tree

Title:

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

Recover the tree without changing its structure.

 

思路:使用中序遍历得到这个序列,找出其中的逆序的两个进行交换。但是,这样需要O(n)的空间。想到

Validate Binary Search Tree 中可以使用全局变量来递归得到中序序列,得到这个O(1)空间的代码

class Solution {
    // Keep the previous value in inorder traversal.
public:
    TreeNode* pre = NULL;
    TreeNode* first = NULL;
    TreeNode* second = NULL;
    
    void recoverTree(TreeNode* root) {
        // Traverse the tree in inorder.
        inOrder(root);
        int v = first->val;
        first->val = second->val;
        second->val = v;
    }
    
    void inOrder(TreeNode* root){
        if (root != NULL) {
            // Inorder traversal: left first.
            inOrder(root->left);
            // Compare it with the previous value in inorder traversal.
            if (pre != NULL && root->val <= pre->val){
                if (first == NULL)
                    first = pre;
                second = root;
            }
            pre = root;
            
            inOrder(root->right);
        }
    }
};

 

posted on 2015-05-12 13:33  月下之风  阅读(181)  评论(0编辑  收藏  举报

导航