The Recover Binary Search Tree problem gives you a BST where exactly two nodes were accidentally swapped. Find those two nodes and swap them back to restore the BST. This medium coding problem uses Morris Traversal (O(1) space) or inorder DFS to find the two "out-of-order" nodes. The BST, DFS, binary tree, and tree interview pattern is demonstrated.
Apple, Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it tests in-order BST traversal with anomaly detection. The key insight: in a valid BST, inorder traversal is strictly increasing; the swapped nodes create at most two "drops" in the sequence.
Inorder traversal + anomaly detection. Perform inorder traversal. Track the previous node. When prev.val > current.val (a drop), record: first anomaly node = prev (first drop), second anomaly node = current (last drop). After traversal, swap the values of the two anomaly nodes.
BST (inorder should be 1,2,3,4,5): nodes 1 and 3 swapped (now reads 3,2,1,4,5 inorder).
Recover BST demonstrates "inorder anomaly detection." The two swapped nodes create one or two violations in the sorted sequence. Always track both first and update second at each violation. The O(1) space solution using Morris traversal is impressive — worth mentioning even if not implementing. Practice "validate BST" and "find inorder successor/predecessor" as foundations.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Lowest Common Ancestor of a Binary Search Tree | Medium | Solve | |
| Convert BST to Greater Tree | Medium | Solve | |
| Kth Smallest Element in a BST | Medium | Solve | |
| Binary Search Tree to Greater Sum Tree | Medium | Solve | |
| Inorder Successor in BST | Medium | Solve |