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

[leetcode] Recover Binary Search Tree

时间:2015-01-06 02:03:43      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

题目:(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);
    }
}

 

[leetcode] Recover Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/fengmangZoo/p/4204971.html

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