Skip to problem
←

Recover Binary Search Tree

Medium 0 attempts

Exactly two node values in a binary search tree were swapped by mistake. Restore the valid BST by swapping those values back.

All values are distinct. Keep every original node and its left/right child links unchanged; only the misplaced values should change. Modify the tree in place. The function's return value is ignored.

Inorder traversal of a valid BST visits values in strictly increasing order. The swapped nodes may be adjacent or far apart in that traversal, and one may be the root.

For root = [3, 1, 4, null, null, 2], swapping values 3 and 2 restores [2, 1, 4, null, null, 3] without changing the tree's shape.

Examples use level-order arrays with null for missing children. Your function receives nodes with val, left, and right properties.

Function contract

Implement recoverTree(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Modify argument 1 in place. The editor compares its final value; the function return value is ignored. Returned trees are displayed as level-order arrays, trimming trailing nulls.

Example 1

Input
root = [1,3,null,null,2]
Output
[3,1,null,null,2]

Example 2

Input
root = [3,1,4,null,null,2]
Output
[2,1,4,null,null,3]
Constraints
  • 2 <= number of nodes <= 1000
  • -2^31 <= Node.val <= 2^31 - 1
  • All values are distinct. Exactly two node values in an otherwise valid strict BST have been swapped.

Recursive Inorder Traversal

Inorder traversal should be strictly increasing. Track the previously visited node and detect a descending adjacent pair whenever previous.val > current.val.

At the first violation, save the previous node as first. At every violation, update second to the current node. If the swapped nodes were adjacent in inorder, there is one violation and these are exactly the two nodes. If they were separated, there are two violations: the earlier larger value and the later smaller value are the misplaced nodes.

Swap their values after traversal. Do not change child links. The guarantee that exactly two distinct values were swapped ensures both candidates exist.

javascript
function recoverTree(root) {
  let first = null,
    second = null,
    prev = { val: -Infinity };
  function inorder(node) {
    if (!node) return;
    inorder(node.left);
    if (node.val < prev.val) {
      if (!first) first = prev;
      second = node;
    }
    prev = node;
    inorder(node.right);
  }
  inorder(root);
  [first.val, second.val] = [second.val, first.val];
}

Time: O(n) | Space: O(h)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript