首页 > 其他 > 详细

[LeetCode#99]Recover Binary Search Tree

时间:2015-01-09 06:54:26      阅读:244      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

[LeetCode#99]Recover Binary Search Tree

原文:http://www.cnblogs.com/airwindow/p/4212332.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!