hardTreeTrees

Recover Binary Search Tree

hardTime: O(n)Space: O(h)

Recognize the pattern

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

Brute force idea

The naive version of Recover Binary Search Tree sounds like this: 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.

Better approach

The deeper shift in Recover Binary Search Tree is this: 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.

Key invariant

At the center of Recover Binary Search Tree is one steady idea: 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.

Watch out for

One easy way to drift off course in Recover Binary Search Tree is this: 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