Lowest Common Ancestor of a Binary Tree
Given the root of a binary tree and two nodes p and q, find their Lowest Common Ancestor (LCA).
The LCA is the lowest/deepest node in the tree that has both p and q as descendants.
A node can also be considered a descendant of itself.
Example Tree
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
For:
p = 5 q = 1
The LCA is:
3
For:
p = 5 q = 4
The LCA is:
5
because 4 is inside the subtree rooted at 5.
Example 1
Input
root = [3,5,1,6,2,0,8,null,null,7,4] p = 5 q = 1
Output
3
Explanation
The tree is:
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
Node 5 is in the left subtree of 3, while node 1 is in the right subtree.
Therefore, the first node where their paths meet is:
3
So the LCA is 3.
Example 2
Input
root = [3,5,1,6,2,0,8,null,null,7,4] p = 5 q = 4
Output
5
Explanation
Node 4 is a descendant of node 5:
5
/ \
6 2
/ \
7 4
Since 5 itself is one of the given nodes and contains 4 in its subtree, 5 is the lowest common ancestor.
Constraints
Hints:
Hint 1
Start from the root and recursively search both subtrees.
Hint 2
If the current node is: NULL
return NULL.
If the current node is either p or q, return the current node.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 12, 2026
Last updated
Aug 13, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output