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

[leetcode] Recover Binary Search Tree

时间:2014-07-03 19:44:18      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

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?

https://oj.leetcode.com/problems/recover-binary-search-tree/

 

思路1:中序遍历生成序列,然后对其中错序的进行调整。 需要额外O(n)的空间。

思路2:中序遍历二叉树,记录当前指针cur的前一个节点pre,如果pre.val大于cur.val,表示有错序,多数情况错序有两次;如果有一次错序,说明就是相邻节点需要被交换。

 

bubuko.com,布布扣
public class Solution {

    private TreeNode pre;
    private TreeNode wrong1;
    private TreeNode wrong2;

    public void recoverTree(TreeNode root) {
        preOrder(root);
        int tmp = wrong1.val;
        wrong1.val = wrong2.val;
        wrong2.val = tmp;

    }

    private void preOrder(TreeNode root) {
        if (root == null)
            return;
        preOrder(root.left);

        if (pre != null && pre.val > root.val) {
            if (wrong1 == null) {
                wrong1 = pre;
                wrong2 = root;
            } else {
                wrong2 = root;
            }

        }

        pre = root;

        preOrder(root.right);

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(15);
        root.left.right = new TreeNode(13);
        root.right.left = new TreeNode(7);

        new Solution().recoverTree(root);

    }

}
View Code

 

参考:

http://blog.csdn.net/worldwindjp/article/details/21694179

[leetcode] Recover Binary Search Tree,布布扣,bubuko.com

[leetcode] Recover Binary Search Tree

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3821290.html

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