We're live on Product Hunt today! Use code PRODUCTHUNT26 for 20% off. Upvote us ↑
DSA Trainer
← All problems
PremiumTree TraversalMedium

Lowest Common Ancestor of a Binary Tree

Asked at:AmazonGoogleMeta

Given a binary tree and two nodes p and q, return their lowest common ancestor (LCA). The LCA is the deepest node that is an ancestor of both p and q. A node is considered an ancestor of itself.

This is a premium problem.

Unlock Lowest Common Ancestor of a Binary Tree with both full courses, DSA and System Design, and every other premium problem.

Problem

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

Input

The root of a binary tree and two tree nodes `p` and `q`.

Output

The LCA node.

Examples

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1

Output: 3

Node 3 is the LCA of nodes 5 and 1.

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4

Output: 5

Node 5 is an ancestor of node 4, so 5 is its own LCA with 4.

The brute-force approach

For each node, find the path from root to p and the path from root to q. Find the deepest node common to both paths.

def find_path(root, target, path):
    if not root: return False
    path.append(root)
    if root == target: return True
    if find_path(root.left, target, path) or find_path(root.right, target, path):
        return True
    path.pop()
    return False

path_p, path_q = [], []
find_path(root, p, path_p)
find_path(root, q, path_q)
# Find last common element
lca = None
for a, b in zip(path_p, path_q):
    if a == b: lca = a
return lca

O(n) but with two separate DFS passes and O(n) space for paths. The recursive single-pass approach below is cleaner.

Time: O(n)Space: O(n)

Spotting the pattern

This is a Tree Traversal problem. The key question to ask yourself:

If left subtree DFS returns node A and right subtree DFS returns node B (both non-null), what does that tell you about the LCA?

Answering that is where it clicks, and it's exactly what the guided walkthrough below builds with you: the pattern reasoning, a progressive hint ladder that never spoils the answer, a row-by-row dry run, the optimized solution, and an in-browser editor to run your code against real test cases.

Premium

Unlock the full guided solution

The Tree Traversal walkthrough for Lowest Common Ancestor of a Binary Tree: the progressive hint ladder, a row-by-row dry run, the optimized code, and an in-browser runner, plus both full courses, DSA and System Design, and every other premium problem.

Already finished Big-O and Hash Maps free? This picks up right where the path leads: same format, harder patterns, the ones that show up in every FAANG-style screen.

What you get

  • The full DSA course: concept lessons, drills, graded tests, and cold-read capstones for every pattern
  • The full System Design course: 20 building-block units for the design round, included at no extra cost
  • Stop going blank on algorithm problems. The hint ladder walks you to the answer without spoiling it.
  • Actually internalize the trace: dry runs walk state row by row so it clicks before you write a line
  • Know when to reach for each pattern. Every problem names the trigger so you spot it next time.
  • Write and run JS or Python in the browser with real test cases on every problem
  • Access every new problem, unit, and pattern guide as they ship weekly
B
Big_Wolverine_7575Founding Member· unprompted on Reddit

“This app finally made it click. I tried NeetCode, CTCI, and YouTube for years and still couldn't solve Two Sum. The beginner mental models for the patterns are genuinely so helpful. THANK YOU.

Full access · both courses

Full access

$49 / year

or $9 / month

Now includes a C++ runner alongside JavaScript and Python.

LeetCode Premium is $159/year and doesn't teach you anything.

Less than one Udemy course, with guided problems instead of passive lectures.

One extra month of job searching costs more than a full year here.

  • Both courses, every unit: DSA + System Design
  • All 150 problems across 33 patterns, plus every new one
  • New problems and units weekly
  • Cancel anytime

Cancel anytime. Not useful within 7 days? Email for a full refund. Secured by Stripe.