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

Recover Binary Search Tree

时间:2014-06-08 15:32:45      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:leetcode      中序遍历   java   

题目

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?

方法

利用BST中序遍历是一个有序的序列。
中序遍历BST,遇到顺序错误的则标记,找到两个错误,交换其值即可。
若只找到一个,则说明第一个标记的后面的结点,是错误的。
    public void recoverTree(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode node = root;
        TreeNode first = null;
        TreeNode second = null;
        TreeNode last = null;
        while (node != null || !stack.isEmpty()) {
            while(node != null) {
                stack.push(node);
                node = node.left;
            }
            TreeNode curNode = stack.pop();
            if (last == null) {
                last = curNode;
            } else {
                if (last.val > curNode.val) {
                    if (first == null) {
                        first = last;
                        second = curNode;
                    } else {
                        second = curNode;
                        break;
                    }
                }
                last = curNode;
            }
            node = curNode.right;
        }
        
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }


Recover Binary Search Tree,布布扣,bubuko.com

Recover Binary Search Tree

标签:leetcode      中序遍历   java   

原文地址:http://blog.csdn.net/u010378705/article/details/28672765

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