Two values got swapped
Repair a search tree in which exactly two node values were swapped by mistake, by finding the two places where the inorder sequence goes down and swapping the values back. About 20 minutes.
Look for the drops
An inorder walk of a valid search tree gives increasing values. If two values were swapped, the list is almost sorted: one value is too big for its place and another is too small.
Walk inorder and compare each value with the previous one. A place where the previous value is bigger than the current one is a drop.
prev = None
for v in inorder_values:
if prev is not None and prev > v:
print("a drop")
prev = v6 follows 1: increasing. No drop.
Which nodes to swap
Suppose the sorted values 1, 2, 3, 4 become 1, 4, 3, 2. The drops are 4 over 3 and 3 over 2. The wrong nodes are the 4, the earlier node of the first drop, and the 2, the later node of the last drop.
If the swapped values were neighbours, such as 1, 3, 2, 4, there is a single drop, 3 over 2, and the pair is that drop. The same rule works: the first node of the first drop, and the second node of the last drop. Swap their values.
if first is None:
first = prev # the first drop
second = v # the last dropAn inorder sequence has two drops. Which two nodes are swapped?
- AThe earlier node of the first drop and the later node of the second drop
- BThe two nodes of the first drop
- CThe two nodes of the last drop
Show the answer
The earlier node of the first drop and the later node of the second drop. The too-big value shows up early, and the too-small one shows up late.
Recover a search tree
You are given the root of a binary search tree with different values in which exactly two nodes had their values swapped by mistake. Fix the tree by swapping the two values back, without changing the structure, and return the root.
root = [3, 1, 4, null, null, 2] → [2, 1, 4, null, null, 3]
2 ≤ number of nodes ≤ 1,000 · different values · exactly two values swapped