Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 → Output: 6
LCA: first node where p and q diverge. If both < root go left, both > root go right, else root is LCA.
TimeO(h)path height
SpaceO(1)pointer only
Current: —
Current
LCA / Path
p, q
Current
—
Ready
Press Play. While both p,q on same side of root: root = root.left or root.right. Else root is LCA.
TimeO(h)path height
SpaceO(h)call stack
✎ Whiteboard
3
⌨ Type It — Iterative
Practice until you don't need to look. The green highlights are the nuances to burn into memory.
═══ LCA of BST — ITERATIVE ═══
PATTERN ▸ BST property (both left or both right) O(h) · O(1)
① LOOP
while root:
② BRANCH
if p.val < root.val and q.val < root.val: root = root.left