码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 99 Recover Binary Search Tree ----- java

时间:2016-10-26 00:04:21      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:class   could   style   恢复   arc   dev   amp   nts   font   

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?

 

给定一个排序二叉树,然后任意交换了其中两个节点,要求在使用常数个空间和不改变结构的前提下恢复原来的二叉树。

 

 

如果用O(n)的空间复杂度,那么直接中序遍历就好了,现在用常数个,那么只需要记录两次就好了,中序遍历的时候,需要动动脑子。

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
   TreeNode pre;        
    TreeNode first;    
    TreeNode second;
    
    public void inorder(TreeNode root){
        if(root == null){
            return;
        }
        inorder(root.left);
        if(pre == null){
            pre = root;
        }else{
            if(pre.val > root.val){
                if(first == null){
                    first = pre;        
                }
                second = root;        
            }
            pre = root;                
        }
        inorder(root.right);
    }
    
    public void recoverTree(TreeNode root) {
        pre = null;            
        first = null;
        second = null;
        inorder(root);
        if(first!=null && second!=null){    
            int tmp = first.val;
            first.val = second.val;
            second.val = tmp;
        }
    }

}

 

 

 

leetcode 99 Recover Binary Search Tree ----- java

标签:class   could   style   恢复   arc   dev   amp   nts   font   

原文地址:http://www.cnblogs.com/xiaoba1203/p/5998745.html

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