Tuesday, March 3, 2015

LeetCode Recover Binary Search Tree

Similar idea with using inorder traversal (Valid binary Search)

Here is the solution for valid binary search
private TreeNode prev;
    public boolean isValidBST(TreeNode root) {
       prev = null;
       return isMonoIncreasing(root);
    }
   
    private boolean isMonoIncreasing (TreeNode p) {
        if (p == null) return true;
        if (isMonoIncreasing(p.left)) {
            if (prev != null && p.val <= prev.val) return false;
            prev = p;
            return isMonoIncreasing(p.right);
        }
        return false;
    }

Here is the solution for the recover binary search
public static TreeNode prev;

    public void recoverTree(TreeNode root) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
//Similar idea with isValidBST using inOrder traversal

        prev = null;
//我们知道只有2个TreeNode 被弄错了
TreeNode[] misOrder = new TreeNode[2];
inorder(root,misOrder);
int temp = misOrder[0].val;
misOrder[0].val = misOrder[1].val;
misOrder[1].val = temp;
}
private static void inorder(TreeNode root, TreeNode[] misOrder) {
if(root == null) return;

inorder(root.left, misOrder);
if(prev!=null && prev.val > root.val){
if(misOrder[0] == null) misOrder[0] = prev;
misOrder[1] = root;
}
//dont forget to update the prev
prev = root;

inorder(root.right, misOrder);
}

No comments:

Post a Comment