3.13
In an in-order walk of a Binary Search Tree (BST) the keys must appear in ascending order.
If exactly two keys are swapped, the in-order sequence will contain at most two “inversions”, i.e. places where a previous key is larger than the current key.
Algorithm (O(n) time, O(h) stack space, or O(1) with Morris traversal):
1. Traverse the tree in-order while remembering the last visited node prev
.
2. Whenever prev.val > curr.val
we have an inversion.
• On the first inversion, record first = prev
and second = curr
.
• On a possible second inversion, update only second = curr
(leave first
unchanged).
3. After the traversal first
and second
are the misplaced nodes. Swapping their values restores the BST.
Back to
Chapter 3