Skip to content

99. Recover Binary Search Tree

Jacky Zhang edited this page Sep 23, 2016 · 1 revision

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?

解题思路为inorder traversal。

我们定义三个变量,prev,first,second,在inorder的print body处插入代码,判断输出是否有序,从而找到顺序不对的两个元素first和second。 最后将这两个node的val交换即可。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    TreeNode prev, first, second;
    
    public void recoverTree(TreeNode root) {
        prev = new TreeNode(Integer.MIN_VALUE);
        inOrder(root);
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
    
    private void inOrder(TreeNode node) {
        if(node == null) return;
        inOrder(node.left);
        if(first == null && prev.val > node.val) {
            first = prev;
        }
        if(first != null && prev.val > node.val) {
            second = node;
        }
        prev = node;
        inOrder(node.right);
    }
}
Clone this wiki locally