[leetcode] Recover Binary Search Tree

题目:(Tree ,DFS)

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?

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

题解:

还是和inorder 遍历联系在一起的,在遍历的时候记录两个被交换的值

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    TreeNode maxfinal=new TreeNode(Integer.MIN_VALUE);
    TreeNode minfinal=new TreeNode(Integer.MAX_VALUE); 
    
    public void recoverTree(TreeNode root) {
        TreeNode min=new TreeNode(Integer.MIN_VALUE);
        TreeNode max=new TreeNode(Integer.MAX_VALUE);       
        check(root.left,min,root);
        check(root.right,root,max);
        int temp=maxfinal.val;
        maxfinal.val=minfinal.val;
        minfinal.val=temp;
        
    }
    
    public void check(TreeNode root,TreeNode min ,TreeNode max){
        if(root==null) return ;
        if(root.val<min.val)
        {
            if(minfinal.val>root.val)
                minfinal=root;
            if(maxfinal.val<min.val)
                maxfinal=min;
        }else if(root.val>max.val)
        {
            if(minfinal.val>max.val)
                minfinal=max;
            if(maxfinal.val<root.val)
                maxfinal=root;
        }
        check(root.left,min,root);
        check(root.right,root,max);
    }
}
原文地址:https://www.cnblogs.com/fengmangZoo/p/4204971.html