KatInterview

Repairing a Search Tree After One Pair of Keys Trades Places

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbinary-search-treemorris-traversalin-order

Last 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:

  1. How you locate the two misplaced nodes, including when they sit next to each other in in-order and when they do not.
  2. A first solution using recursion or a stack, and its space cost.
  3. A version that needs O(n) time and O(1) extra space, with no recursion and no explicit stack.
  4. 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.