#236

Lowest Common Ancestor of a Binary Tree

Medium Postorder search

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

?The problem

Given two nodes p and q in a binary tree, return their lowest common ancestor (a node may be an ancestor of itself).

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

◎Understanding

Really asking: the deepest node that has both p and q below it (or is one of them).

Why this works: search both sides. If p is found on one side and q on the other, this node is where they split.

Example: p = 5, q = 1 in a tree rooted at 3 with children 5 and 1

left finds 5, right finds 1 → answer 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Storing full root-to-node paths in lists — works, but uses more memory and code.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(h).
Topic: Binary Trees
🎬 Episodes 53–60: video coming soon