天题系列: 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?

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

    }

}

 

你可能感兴趣的:(Binary search)