Lowest Common Ancestor of a Binary Tree
Problem Statement
You are given the root of a binary tree and two nodes p and q that are both in the tree. The tree is not sorted, so a node's value tells you nothing about where it is.
Find the lowest common ancestor (LCA) of p and q. This is the lowest node that has both p and q below it. A node counts as its own ancestor.
Return the node itself, not its value.
root, the root of a binary tree, and two different node pointers p and q.
The node that is the lowest common ancestor of p and q.
5 is in the left subtree of 3 and 1 is in the right subtree, so 3 is the first node that splits them.
4 is below 5. A node counts as its own ancestor, so the answer is 5 itself.
2 is the child of 1, so the answer is 1.
- • The number of nodes in the tree is in the range [2, 10^5].
- • −10^9 ≤ Node.val ≤ 10^9
- • All Node.val are unique.
- • p ≠ q
- • p and q will exist in the tree.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each node, check whether its subtree holds both p and q; keep the deepest one that does
Two DFS calls record the root-to-p and root-to-q paths; the last node both paths share is the answer
Each node asks its children what they found; if both sides found something, this node is the answer
A node is a common ancestor when its subtree contains both p and q. So check every node: search its subtree for p and for q. Among all the nodes that pass, the deepest one is the lowest common ancestor.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.