Leetcode 99. Recover Binary Search Tree

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.
例子:[1,2,3,4]这样一个bst,2是根节点,如果交换14,会变为[4,2,3,1],如果交换34,会变为[1,2,4,3]。

思路:如果一个bst没有被错误放置,那么中序遍历的结果应该是一个递增序列。现在交换了其中两个节点,从上面的例子我们能看到会出现1次或者2次的降序,因此我们只要中序遍历这个bst,在遇到降序的时候,记录下降序的节点。如果只有一次降序,要交换的两个点就是这次降序的两个节点;如果出现了两次降序,那么第一个点是第一次降序的较大节点,第二个点是第二次降序的较小节点。
下面的中序遍历用循环解法给出。

public void recoverTree(TreeNode root) {
    if (root == null) {
        return;
    }

    TreeNode swap1 = null;
    TreeNode swap2 = null;
    TreeNode pre = null;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur = root;
    while (cur != null || !stack.isEmpty()) {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.pop();
        if (pre != null && pre.val >= cur.val) {
            if (swap1 == null) {
                swap1 = pre;
                swap2 = cur;
            } else {
                swap2 = cur;
            }
        }
        pre = cur;
        cur = cur.right;
    }

    int tmp = swap1.val;
    swap1.val = swap2.val;
    swap2.val = tmp;
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/65c3b61c4e17
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞