LeetCode 99: Recover Binary Search Tree

/**
 * 99. Recover Binary Search Tree
 * 1. Time:O(n)  Space:O(logn)
 * 2. Time:O(n)  Space:O(1)
 */

// 1. Time:O(n)  Space:O(logn)
class Solution {
    
    TreeNode p1 = null;
    TreeNode p2 = null;
    TreeNode prev = null;

    public void recoverTree(TreeNode root) {
        inOrder(root);
        int tmp = p1.val;
        p1.val = p2.val;
        p2.val = tmp;
    }
    
    public void inOrder(TreeNode root){
        if(root==null) return;
        if(root.left!=null) inOrder(root.left);
        if(prev!=null && root.val<prev.val){
            if(p1==null){
                p1 = prev;
                p2 = root;
            }else{
                p2 = root;
            }
        }
        prev = root;
        if(root.right!=null) inOrder(root.right);
    }
}

// 2. Time:O(n)  Space:O(1)
class Solution {
    public void recoverTree(TreeNode root) {
        TreeNode first = null;
        TreeNode second = null;
        TreeNode tmp = null;
        TreeNode prev = null;
        TreeNode cur = root;
        while(cur!=null){
            if(prev!=null && cur.val<=prev.val){
                if(first == null) first = prev;
                second = cur;
            }
            if(cur.left == null){
                prev = cur;
                cur = cur.right;
            }else{
                tmp = cur.left;
                while(tmp.right!=null && tmp.right!=cur)
                    tmp = tmp.right;
                if(tmp.right == null){
                    tmp.right = cur;
                    cur = cur.left;
                }else{
                    tmp.right = null;
                    prev = cur;
                    cur = cur.right;
                }
            }
        }
        int val = first.val;
        first.val = second.val;
        second.val = val;
    }
}
posted @ 2020-04-29 11:10  AAAmsl  阅读(70)  评论(0编辑  收藏  举报