Recover Binary Search Tree

medium

You are given the root of a binary search tree where the values of exactly two nodes were swapped by mistake. Recover the tree by restoring those two nodes (without changing its structure) and return the root.

The tree is given in level-order (breadth-first), using null for missing children; return it in the same format.

Hints

What is always true about a BST's inorder traversal?
A swap breaks the ascending order at one or two places — find them.
Track the previous node; a dip (prev.val > cur.val) marks an offender.

Common doubts

If the two swapped nodes are adjacent in the inorder order there is a single dip; otherwise there are two. The 'first from the first dip, second from the last dip' rule handles both.
A BST's inorder values are exactly the sorted values, so writing the sorted values back in inorder order must produce the correct BST — but it's O(n) space.
Yes — Morris inorder traversal threads the tree to avoid the recursion/stack, giving true O(1) extra space.

Interview follow-ups

The single-pass rule no longer suffices; you'd need to detect all anomalies and reconstruct, e.g. via the sort approach.
It temporarily links each node's inorder predecessor to it, walks without a stack, then restores the links.

Fun facts

  • This is the classic test of whether you truly understand that inorder of a BST is sorted.
  • The one-dip vs two-dip distinction trips up most first attempts — it's the whole trick.

Asked at

AmazonMicrosoftFacebookGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [1, 3, null, null, 2]
Output: [3, 1, null, null, 2]
1 and 3 were swapped; restoring them yields a valid BST.
Example 2
Input: root = [3, 1, 4, null, null, 2]
Output: [2, 1, 4, null, null, 3]
2 and 3 were swapped; swapping them back recovers the BST.
Constraints

- The number of nodes is in the range [2, 10^4] - -2^31 <= Node.val <= 2^31 - 1 - Exactly two nodes were swapped

Solve this problem →