#99

Recover Binary Search Tree

Medium Inorder to find swapped pair

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Exactly two nodes of a BST had their values swapped by mistake. Fix the tree without changing its structure.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: two values were swapped by mistake; fix them.

Why this works: inorder should be increasing. The swap creates one or two "drops"; the first wrong node is at the first drop, the second at the last drop.

Example: inorder 1, 3, 2, 4 (3 and 2 swapped)

drop at 3 > 2 → first 3, second 2swap back → 1, 2, 3, 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Assuming there are always two drops — adjacent swapped nodes create only one.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h) (Morris traversal brings it to O(1)).
Topic: Binary Search Trees
🎬 Episodes 61–63: video coming soon