Tuesday, August 13, 2013

[LeetCode] Recover Binary Search Tree

Thought: Recursion way is trivial.

Code:
public class Solution {
    public static TreeNode previous, first, second;
    public void recoverTree(TreeNode root) {
        previous = null;
        first = null;
        second = null;
        inorder(root);   
        swap(first, second);
    }
    public void inorder(TreeNode root) {
        if (root == null) return;
        if (root.left != null) inorder(root.left);
        dosomething(root);
        if (root.right != null) inorder(root.right);
    }
    public void dosomething(TreeNode root) {
        if (previous != null && root.val < previous.val) {
            if (first == null) {
                first = previous;
                second = root;
            }else second = root;
        }
        previous = root;
    }
    public void swap(TreeNode first, TreeNode second) {
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
}

Note: There exists a smart traversal method -> Inorder Morris Traversal 
No Recursion, no stack!!!
   
 public void inorder(TreeNode root) {
        if (root == null) return;
        TreeNode cur = root;
        while (cur != null) { 
            if (cur.left == null) { // no left child -> visit and step right
                dosomething(cur);
                cur = cur.right;
            }else {
                TreeNode tmp = cur.left; 
                while (tmp.right != null && tmp.right != cur) { // let tmp step rightest
                    tmp = tmp.right;
                }
                if (tmp.right == null) { // tmp is leaf -> build circle and step left
                    tmp.right = cur;
                    cur = cur.left;
                }else {
                    tmp.right = null; // tmp is already in circle -> destroy circle, visit, and step right
                    dosomething(cur);
                    cur = cur.right;
                }
            }
        }

    }

No comments:

Post a Comment