Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure.

  • Time: O(n) Space: O(1)
public class RecoverBinarySearchTree {
    private TreeNode error1 = null;
    private TreeNode error2 = null;
    private TreeNode last = new TreeNode(Integer.MIN_VALUE);
    public void recoverTree(TreeNode root) {
        dfs(root);
        int temp = error1.val;
        error1.val = error2.val;
        error2.val = temp;
    }
    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        if (error1 == null && root.val < last.val) {
            error1 = last;
        }
        if (error1 != null && root.val < last.val) {
            error2 = root;
        }
        last = root;
        dfs(root.right);
    }
}

results matching ""

    No results matching ""