ExamAdda Logo

Lowest Common Ancestor of a Binary Tree

Easy

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

2 <= number of nodes <= 10^5
-10^9 <= Node.val <= 10^9
All Node.val are unique.
p != q
p and q will exist in the tree.

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

ExamAdda Technical Review Team

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.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output