Problem Description
Given the root of a binary search tree (BST) where exactly two nodes have been swapped by mistake, restore the BST without changing its structure.
Key Insights
- In a valid BST, an in-order traversal produces a sorted sequence.
- A swapped node pair causes a deviation from the sorted order. There can be one or two such violations.
- By tracking the previous node during an in-order traversal, we can identify nodes where the value order is incorrect.
- After finding the two nodes, swap their values to fix the tree.
- While the straightforward recursive in-order traversal uses O(n) space (due to the recursion stack), the Morris traversal technique can achieve O(1) space.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) in the recursive approach (or O(1) using Morris Traversal)
Solution
The solution involves performing an in-order traversal of the BST to detect the two nodes that have been swapped. During the traversal, we maintain a pointer to the previously visited node. When we encounter a node that is less than its previous node, we record the two nodes that violate the BST invariant. In cases where the swapped nodes are not adjacent, we will see two such violations; otherwise, we see only one. Finally, we swap the values of the two incorrect nodes, thereby restoring the BST.