#235

Lowest Common Ancestor of a Binary Search Tree

Medium Split point

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

?The problem

Return the lowest common ancestor of two nodes p and q in a BST.

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

◎Understanding

Really asking: the split point of p and q.

Why this works: both smaller → go left; both bigger → go right; otherwise you're at the split.

Example: tree 6 (2 (0, 4), 8 (7, 9)), p 2, q 8

2 < 6 < 8 → split at 6

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using the general binary-tree LCA — it works but doesn't use the BST ordering.

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