首页 > 其他 > 详细

Recover Binary Search Tree

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

题目

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!