[LeetCode#99]Recover Binary Search Tree

The problem:

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?

 

My analysis:

The idea behind this problem is so elegant!!!
The key idea: we can get the swapped nodes from the inroder traversal series of the binary tree. It includes following two conditions:
1. the two swapped nodes in neighbour with each other.
Inorder traversal series: 1 ,2 ,3 ,5 ,4, 6, 7

2. the two swapped nodes are not in neighbour with each other.
Inorder traversal series: 1, 5, 3, 4, 2, 6, 7

The two cases needed to be tackled differently.
In situation 1, we would detect only one violation, the swapped nodes should be 5, 4
In situation 2, we would detect two violations, the swapped nodes should be: the pre node(5) in the first violation, and the post node(2) in the second violation.

skills in implementation:
1. Since Java pass arguments by value, we should use the ArrayList to record the target nodes we have figured out during the recursion process.
2. Swap nodes by value rather than by pointer. (don not fool in thinking about recording the parent's pointer)

 

My solution:

public class Solution {
    public void recoverTree(TreeNode root) {
        
        if (root == null) //note. the declaration's return value is void 
            return;
        
        ArrayList<TreeNode> pre = new ArrayList<TreeNode> ();
        ArrayList<TreeNode> ret = new ArrayList<TreeNode> ();
        pre.add(null);
        
        helper(root, pre, ret);//inorder to track the result, we use ArrayList.
        
        if (ret.size() > 0) {
            
            int temp = ret.get(0).val;
            ret.get(0).val = ret.get(1).val;
            ret.get(1).val = temp;
        }
        
        return;
    }
    
    private void helper(TreeNode root, ArrayList<TreeNode> pre, ArrayList<TreeNode> ret) {
        
        if (root == null)
            return;
        
        helper(root.left, pre, ret);
        
        if (pre.get(0) != null && pre.get(0).val >= root.val) {
            if (ret.size() == 0) {
                ret.add(pre.get(0));
                ret.add(root);
            } else {//we have already detected a violation 
                ret.set(1, root);
            }
        }
        pre.set(0, root);
        
        helper(root.right, pre, ret);
        
        return;
    }
}

 

posted @ 2015-01-09 01:30  airforce  阅读(118)  评论(0编辑  收藏  举报