Introduction
Recover BST means:
- fixing Binary Search Tree
where two nodes
were swapped accidentally
BST Property:
Left subtree values < Root value < Right subtree values Goal:
- detect swapped nodes
- restore BST ordering
- without rebuilding tree
Example:
Incorrect BST:3
/ \
1 4
/
2
Correct BST:
2
/ \
1 4
/
3
Explanation:
Two nodes violate BST inorder ordering and must be swapped back. This problem is one of the most important applications of:
Inorder DFS TraversalConstraints
1 <= Number of Nodes <= 10^5 Approach : Inorder DFS Detection
Explanations:
Explanation:
The idea is:
- inorder traversal
of BST must remain sorted - detect misplaced nodes
- swap values back
Traversal Order:
Left → Root → RightSteps:
- Perform inorder traversal.
- Compare previous node.
- Detect ordering violation.
- Store swapped nodes.
- Swap node values back.
Violation Condition:
previous.value > current.valueThis approach:
- uses DFS recursion
- leverages BST sorted property
Dry Run
Inorder Traversal:1 3 2 4
Violation:
3 > 2
Swapped nodes detected:
3 and 2
Swap values back.
BST recovered.
Practice :