Lesson 37 of 86IntermediatePro Interactive Lesson

Finding the Lowest Common Ancestor

Follow the two root paths and locate the deepest node they have in common.

Core Intuition & How It Works

The Lowest Common Ancestor (LCA) of two nodes p and q is the deepest node that has both p and q as descendants. A single postorder DFS returns whichever target it finds and identifies the split point where both subtrees report a match.

In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.

Time & Space Complexity

MetricComplexity
Time ComplexityO(n) general tree, O(h) BST
Space ComplexityO(h)
Topic ChapterChapter 7: Trees
Difficulty LevelIntermediate

Key Pattern to Recognize

If both left and right recursive calls return non-null, the current node is the LCA; otherwise propagate the non-null result upward.

Common Pitfalls & Edge Cases

Forgetting that a node can be an ancestor of itself, or not verifying both nodes exist when the problem allows missing targets.

Real-World & Technical Interview Applications

Git merge-base commits, network routing hierarchies, taxonomy queries, and distance between tree nodes.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.