Recover Binary Search Tree (LeetCode 99): Solution and Explanation

Medium
Tree
Depth First Search
Binary Search Tree
Binary Tree

Exactly two nodes in a binary search tree had their values swapped by mistake. You need to put the tree back into valid BST order by fixing those values, without rebuilding or restructuring the tree.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The key fact about a BST is that an in-order traversal visits its values in strictly increasing order. If two values are swapped, that sequence is sorted except for the two misplaced entries. So a brute force approach is easy to see: traverse in order into a list, sort a copy, and compare to find which two values differ, then write them back. That works but uses O(n) extra memory and an unnecessary sort.

Look more closely at what a swap does to a sorted sequence. If you swap two adjacent values, like turning 1 2 3 4 into 1 3 2 4, you get one place where a value is bigger than the next one. If you swap two distant values, like 1 4 3 2 5, you get two such drops: 4 then 3, and 3 then 2. In both cases the first wrong node is the larger element of the first drop, and the second wrong node is the smaller element of the last drop.

That means you never need to store the sequence. Walk the tree in order while remembering the previously visited node prev. Whenever prev.val > node.val, record prev as first if it is the first drop you have seen, and always overwrite second with node. After the traversal, swapping the values of first and second restores the tree.

Approach: In-order traversal with a previous pointer

  1. Initialize first, second and prev to None.
  2. Run a recursive in-order traversal: visit the left subtree, then the current node, then the right subtree.
  3. At each node, if prev exists and prev.val > node.val, the pair is out of order.
  4. On the first such drop set first = prev; on every drop set second = node, so adjacent and distant swaps are both handled.
  5. Set prev = node before moving on to the right subtree.
  6. After the traversal, swap first.val and second.val to repair the tree in place.

Step-by-step example

root = [1, 3, null, null, 2]  (1 has left child 3, and 3 has right child 2)
  1. The in-order sequence of this tree is 3, 2, 1, which should have been 1, 2, 3.
  2. Visiting 3 first sets prev to the node with 3.
  3. Visiting 2: prev.val = 3 > 2, this is the first drop, so first is the node 3 and second is the node 2.
  4. Visiting 1: prev.val = 2 > 1, a second drop, so first stays at 3 and second becomes the node 1.
  5. Swapping the values of first and second turns 3 into 1 and 1 into 3, giving [3, 1, null, null, 2], whose in-order sequence is 1, 2, 3.

Code: Python, Java, C++

1class Solution:
2    def recoverTree(self, root: Optional[TreeNode]) -> None:
3        first = second = prev = None
4        def inorder(node):
5            nonlocal first, second, prev
6            if not node:
7                return
8            inorder(node.left)
9            if prev and prev.val > node.val:
10                if not first:
11                    first = prev
12                second = node
13            prev = node
14            inorder(node.right)
15        inorder(root)
16        first.val, second.val = second.val, first.val

Time and space complexity

Time

O(n)

Every node is visited exactly once by the in-order traversal and the work per node is constant.

Space

O(h)

The recursion stack holds one frame per level, so it is proportional to the tree height h, which is O(log n) when balanced and O(n) for a skewed tree.

Other approaches

Collect, sort and compare (time O(n log n), space O(n))

Store the in-order values in a list, sort a copy and find the two positions that differ, then walk the tree again to fix them. Easy to reason about but uses linear memory and a sort.

Morris traversal (time O(n), space O(1))

Morris in-order traversal threads temporary right pointers back to predecessors so no stack is needed. The same prev and drop logic applies, giving true constant extra space at the cost of trickier code.

Common mistakes

  • Setting second only on the second drop breaks the adjacent swap case, where there is just one drop and second must be the node from that drop.
  • Overwriting first on every drop instead of only the first one picks the wrong larger value when the swapped nodes are far apart.
  • Updating prev before checking the comparison makes prev equal to the current node, so no drop is ever detected.
  • Swapping the nodes themselves rather than their values is unnecessary and requires relinking parents; the problem only needs the values fixed.

Frequently asked questions

How do you find the two swapped nodes in a BST?

Do an in-order traversal and watch for places where the previous value is larger than the current one. The first wrong node is the previous node at the first drop and the second is the current node at the last drop.

Why can there be one or two inversions?

If the swapped values were next to each other in sorted order, the in-order sequence has a single drop. If they were further apart, the larger value creates one drop where it sits too early and the smaller creates another where it sits too late.

Can you recover the BST in O(1) space?

Yes, with Morris traversal, which simulates in-order traversal by temporarily linking each predecessor back to its successor. The reference code uses recursion, which costs O(h) stack space.

Do I need to return anything?

No. The function fixes the tree in place by swapping the two values, and the tree structure stays exactly the same.