Repairing a Search Tree After One Pair of Keys Trades Places
Trees & GraphsModel answerLast updated
Two keys in a binary search tree were exchanged by mistake. Restore ordering by swapping values back, keeping the shape intact, in linear time and constant extra space.
A binary search tree was corrupted: exactly two of its nodes had their keys exchanged. Every other key is in its original place.
Write a procedure that takes the root and repairs the tree in place so that an in-order walk yields keys in non-decreasing order. Only the stored values may be changed. The links between nodes must end up exactly as they started.
Input: the root of the damaged tree (it may be empty or a single node, so your code must not crash).
Output: nothing is returned. The tree is modified so it is a valid BST again.
Example: a tree with root 3, left child 1, right child 4, and 4 having a left child 2. Its in-order sequence is 1 3 2 4. After the repair it should read 1 2 3 4.
What to cover in your answer:
- How you locate the two misplaced nodes, including when they sit next to each other in in-order and when they do not.
- A first solution using recursion or a stack, and its space cost.
- A version that needs O(n) time and O(1) extra space, with no recursion and no explicit stack.
- Time and space analysis, plus the edge cases you would test.
Hints
Hint 1
A valid BST read in order is sorted. A single swap turns that sorted sequence into one with exactly two elements exchanged. How many places can the sequence go 'downhill' (a value larger than its successor)?
Hint 2
Track the previously visited node during the in-order walk. At the first downhill pair, the earlier node is misplaced. At the last downhill pair, the later node is misplaced. If there is only one downhill pair, both nodes come from it.
Hint 3
To avoid O(h) space, temporarily make each in-order predecessor's empty right pointer point back to the current node (Morris threading), then remove it when you return. Be careful not to stop the walk early, or the threads stay in the tree.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The in-order traversal of a valid BST is sorted. If two keys trade places, the in-order sequence is a sorted list with two elements exchanged. So the problem becomes:
- Walk the tree in order and find the two out-of-place nodes.
- Swap their
valfields. The structure is never touched.
Finding the two nodes
Keep prev, the node visited just before the current one. A descent is a point where prev.val > cur.val.
- Non-adjacent swap.
1 2 3 4 5 6becomes1 5 3 4 2 6. There are two descents:(5,3)and(4,2). The larger value moved left, so the first culprit isprevof the first descent (5). The smaller value moved right, so the second culprit iscurof the second descent (2). - Adjacent swap.
1 2 3 4becomes1 3 2 4. There is one descent,(3,2), and both culprits come from that single pair.
One rule handles both cases:
on descent:
if first is None: first = prev
second = cur # always overwrite
With one descent, second is that pair's cur. With two, it is overwritten by the later one.
Why exactly these? If the sorted values are a1 ≤ ... ≤ an and positions i < j are swapped, then position i now holds a larger value than its right neighbor, and position j holds a smaller value than its left neighbor. If j = i+1 these coincide as one descent. All other adjacent pairs are untouched and still ordered.
Approach 1: stack or recursion
Do a standard in-order traversal, apply the rule above, then swap the values. This is O(n) time and O(h) space, where h is the height. On a skewed tree that is O(n), so it misses the constant-space target.
Approach 2: Morris traversal (O(1) space)
Morris traversal temporarily threads the tree so we can return to ancestors without a stack.
At node cur:
- No left child: visit
cur, then go tocur.right. - Has left child: find
pred, the rightmost node incur.left.- If
pred.rightis empty: setpred.right = cur(thread), go left. - If
pred.rightiscur: the left subtree is done. Remove the thread, visitcur, go right.
- If
Nodes are visited in exact in-order, because a node with a left subtree is visited only after returning through its predecessor's thread, i.e. after the whole left subtree.
def recover_tree(root):
first = second = prev = None
cur = root
def visit(node):
nonlocal first, second, prev
if prev is not None and prev.val > node.val:
if first is None:
first = prev
second = node
prev = node
while cur:
if cur.left is None:
visit(cur)
cur = cur.right
else:
pred = cur.left
while pred.right and pred.right is not cur:
pred = pred.right
if pred.right is None:
pred.right = cur # create thread
cur = cur.left
else:
pred.right = None # remove thread
visit(cur)
cur = cur.right
if first and second:
first.val, second.val = second.val, first.val
Check on the example: in-order is 1 3 2 4, one descent (3,2), so first=3, second=2. Swapping gives 1 2 3 4.
Complexity
- Time O(n). Predecessor searches look quadratic, but each edge is walked a constant number of times: once while finding a predecessor to create a thread, once when finding it again to remove it, plus ordinary descent. Total work is linear.
- Space O(1). Only a few pointers:
cur,pred,prev,first,second.
| Approach | Time | Extra space | Notes |
|---|---|---|---|
| Collect in-order, sort, write back | O(n log n) | O(n) | Simple, but too slow and large |
| Recursive or stack in-order | O(n) | O(h) | Clean, O(n) on skewed trees |
| Morris traversal | O(n) | O(1) | Temporarily mutates pointers |
Edge cases
- Adjacent in-order nodes: one descent, handled by the overwrite rule.
- Parent/child or root involved: no special case, since only in-order positions matter.
- Two-node tree (root
1, left child2): one descent, swap fixes it. - Skewed tree: Morris is still O(n) time and O(1) space, where stack approaches degrade.
- Duplicates: use strict
>so equal neighbors are not flagged. - Empty or single node: no descent is found, the final guard prevents a crash.
Common mistakes
- Breaking out of the loop early once the second descent is found. With Morris this leaves threads in the tree and corrupts it. Always finish the traversal.
- Setting
secondonly whenfirstis unset, which fails for non-adjacent swaps. - Picking
curinstead ofprevfor the first culprit (or the reverse for the second). - Swapping node links instead of values, which is unnecessary and error-prone.
- Claiming Morris is read-only. It mutates pointers temporarily, so it is unsafe if other threads read the tree concurrently. Mention this trade-off.
Validation
Test with an adjacent swap, a non-adjacent swap, a swap involving the root, a skewed tree, and a two-node tree. After the fix, run an in-order check that the sequence is sorted and confirm that the structure (and no leftover thread) is intact.