Problem Statement

Recover Binary Search Tree

You are given the root of a binary search tree. A binary search tree, or BST, is a tree where every node holds a number, and the rule is: everything to the left of a node is smaller, and everything to the right is larger. Someone made a mistake and swapped the values of exactly two nodes. Your job is to fix it and put those two values back where they belong, without moving any nodes around or changing the shape of the tree. Only the two swapped values need to switch back.

hardTreeTreesTime: O(n) · Space: O(h)

Signals to notice

two nodes swapped in BSTin-order traversal should be sortedfind the anomalies

Brute force first

In-order traversal to array, find the two swapped elements, swap them back. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

In-order traversal tracking the previous node. When you find prev > current, that's an anomaly. The first anomaly gives the first swapped node; the second anomaly gives the second. Swap their values. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on root=[3,1,4,null,null,2] (in-order node values: 1,3,2,4)

Visit node=1: prev=null -> no check. Set prev=1. (first=null, second=null)
Visit node=3: prev=1, 1>3? no. Set prev=3.
Visit node=2: prev=3, 3>2? YES (inversion #1) -> first=null so first=node(3); second=node(2). Set prev=2.
Visit node=4: prev=2, 2>4? no. Set prev=4. Traversal done.
Only one inversion found -> first=node(3), second=node(2).
Swap values: first.val,second.val = 2,3 -> node(3) becomes 2, node(2) becomes 3.
Returned tree: [2,1,4,null,null,3] (in-order now 1,2,3,4).

What must stay true

In a valid BST, in-order traversal is strictly increasing. A swap creates at most two 'inversions' where prev > current. The first inversion's prev and the second inversion's current are the swapped nodes. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

first = second = prev = null
inorder(node):
  if node == null: return
  inorder(node.left)
  if prev != null and prev.val > node.val:
    if first == null: first = prev      # first inversion
    second = node                       # always update second
  prev = node
  inorder(node.right)
inorder(root); swap(first.val, second.val)

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

When the swapped nodes are adjacent in in-order, there's only ONE inversion — both swapped nodes come from the same violation. Handle this case by setting the second node at the first inversion and updating if a second inversion is found. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trees Pattern