Saturday, January 10, 2015

LeetCode 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?
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private TreeNode pre;
    private TreeNode first;
    private TreeNode second;
    
    public void recoverTree(TreeNode root) {
        // Adopt inorder traversal
        // In inorder traversal, the node order is ascending.
        
        // We should consider the following two situations:
        // 1 3 5 (skip) 4 7: one skip --- first is 5, second is 4
        // 1 3 7 (skip) 5 (skip) 4: two skips --- first is 7, second is 4
        
        pre = null;
        first = null;
        second = null;
        
        inorder(root);
        
        // Exchange the values of "first" node and "second" node
        int tmp = first.val;
        first.val = second.val;
        second.val = tmp;
    }
    
    private void inorder(TreeNode node)
    {
        if (node == null)
            return;
            
        inorder(node.left);
        
        // Visit center node
        if (pre == null)
            pre = node;
        else
        {
            // Skip
            if (pre.val > node.val)
            {
                // The first skip
                if (first == null)
                {
                    first = pre;
                    second = node;
                }
                // The second skip
                else
                    second = node;
            }
            
            pre = node;
        }
        
        inorder(node.right);
    }
}

No comments:

Post a Comment