Recover Binary Search Tree
Master this topic with zero to advance depth.
Recover Binary Search Tree
Swapped nodes fix.
Level I: Inorder to Array (Identify Swaps)
Intuition
In a sorted array, the elements are always in increasing order. If two elements are swapped, we will find either one or two points where arr[i] > arr[i+1].
Thought Process
- Perform inorder traversal to get all values.
- In the sorted values, find the two values that are out of place.
- Traverse the tree again and swap these two values back.
Detailed Dry Run
| Tree Inorder | Swapped Pairs | First Node | Second Node |
|---|---|---|---|
| [1, 3, 2, 4] | (3, 2) | 3 | 2 |
| [3, 2, 1] | (3, 2), (2, 1) | 3 | 1 |
Level II: Iterative Inorder (Stack)
Intuition
Instead of checking sortedness in an array, we can do it on the fly using a stack during an iterative inorder traversal. We maintain a prev pointer and identify where prev.val > current.val.
Logic
- Use a stack to perform inorder traversal.
- Whenever
prev.val > current.val, identifying the first and last out-of-order nodes. - Swap values of
firstandsecond.
Detailed Dry Run
Stack: [1, 3, 2]. Pop 3, prev=3. Pop 2, current=2. prev > current! first=3, second=2. Result: swap(3, 2).
Level III: Optimal (In-place Inorder)
Intuition
Thought Process
We can find the swapped nodes during a single inorder traversal without storing the whole tree. We keep tracks of the prev node seen. If prev.val > current.val, we have found an anomaly.
There are two cases:
- Adjacent swaps: Only one anomaly point.
- Non-adjacent swaps: Two anomaly points (first anomaly's
prevand second anomaly'scurrent).
Complexity
- Time:
- Space: (Recursive stack)
Detailed Dry Run
| Prev | Current | Anomaly? | First | Second |
|---|---|---|---|---|
| 3 | 2 | Yes (3>2) | 3 | 2 |
| 2 | 1 | Yes (2>1) | (keep 3) | 1 |
⚠️ Common Pitfalls & Tips
You must update second in every anomaly found. In Case 2 (non-adjacent swaps), second will be updated twice, correctly identifying the further node.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.