码迷,mamicode.com
首页 > 其他好文 > 详细

天题系列: Recover Binary Search Tree

时间:2015-06-10 06:32:31      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

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?

ref

http://www.cnblogs.com/springfor/p/3891390.html

  1
  /  5   3
    /
   4
         2

just like in the ref" 所以在中序便利时,遇见的第一个顺序为抵减的两个node,大的那个肯定就是要被recovery的其中之一,要记录。" 

 

in order search 的缘故是因为这样可以保证左面能先被traverse到,就符合了找到第一个swap点的目的

public class Solution {
    TreeNode first, second, pre;
    public void recoverTree(TreeNode root) {
        if(root==null) return;
        inorder(root);
        if(first!=null && second!=null){
            int tmp=first.val;
            first.val = second.val;
            second.val = tmp;
        }
        return;
    }
    private void inorder(TreeNode node){
        if(node==null) return;
        inorder(node.left);
        if(pre==null){
            pre=node;
        }else{
            if(pre.val>node.val){
                if(first==null){
                    first=pre;
                }
                second = node; //keep moving on to find the second on the right side
            }
            pre = node;
        }
        inorder(node.right);
    }
}

 

天题系列: Recover Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4565038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!