[leedcode 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?

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode firstNode;
    TreeNode secondNode;
    TreeNode pre;
    public void recoverTree(TreeNode root) {
        //对于二叉搜索树来讲,中序遍历应该是递增的,本题要求O(1)空间,出发点就是中序遍历的变形
        //在中序遍历的过程中,需要找到fisrtWrongNode和secondWrongNode,本题最主要的是,使用pre全局遍历,
        /*递归的时候使得pre=root,达到pre能够保存root前置节点的作用,通过比较root和pre的值,找到逆序对,
        如果两个数相邻置换,则逆序对只有一个,
        如果两个数不相邻,逆序对有两个,此时需要更新secondWrongNode*/
        if(root==null) return;
        inOrder(root);
        swap(firstNode,secondNode);
    }
    public void inOrder(TreeNode root){
        if(root==null) return;
        inOrder(root.left);
       /* if(pre!=null&&firstNode==null&&root.val<pre.val){
            firstNode=pre;
        }
        if(pre!=null&&firstNode!=null&&root.val<pre.val){
            secondNode=root;
        }可被下面一个if语句替换*/
        if(pre!=null&&root.val<pre.val){
            if(firstNode==null) firstNode=pre;
            secondNode=root;
        }

        pre=root;
        inOrder(root.right);
    }
    public void swap(TreeNode s1,TreeNode s2){
        int temp=s1.val;
        s1.val=s2.val;
        s2.val=temp;
    }
}

 

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