Binary Tree · Traversal

Lowest Common Ancestor in Binary Tree

Find the lowest node that is ancestor of both p and q using recursive signal propagation.

DFSBottom-up RecursionInterview Essential

Key concepts at a glance — for those who already know the basics.

Problem Statement

Lowest Common Ancestor of a Binary Tree

Return the lowest node in the tree that has both p and q as descendants. A node can be a descendant of itself, so ancestor cases are valid answers.

Core Rule: both sides non-null -> current node is LCA.

01

Intuition

Base hit

If node is null, p, or q, return immediately as recursion signal.

Signal merge

Collect left and right return values, then combine at parent.

Split point

The first node getting both signals is the lowest common ancestor.

02

Diagram

Split Case - LCA = 3

3516208left=5 and right=1 -> return 3

Ancestor Case - LCA = 5

356274p is ancestor of q -> return p (5)
03

Dry Run

CallLeftRightReturn
lca(5)--5
lca(1)--1
lca(3)513 (LCA)
lca(4)--4
lca(5,4 case)645 (LCA)
04

Complexity

Time Complexity

O(n)

Each node is visited once.

Space Complexity

O(h)

Recursion stack depth, where h is tree height.

Interview tip: Explain split case and ancestor case before coding.

Ready to see it in action?

Step through the visualizer to watch the algorithm state update live.

Open Visualizer