Introduction
The Lowest Common Ancestor (LCA) problem is an important and frequently asked DSA interview question related to trees. While the basic idea looks simple, interviewers often expect a deep understanding of logic, edge cases, and BST properties.
In simple words, the Lowest Common Ancestor of two nodes is the lowest (closest) node in the tree that connects both nodes.
What is a Binary Search Tree (BST)?
A Binary Search Tree (BST) is a binary tree that follows a strict ordering rule:
All nodes in the left subtree have values less than the root
All nodes in the right subtree have values greater than the root
Because of this property:
Searching becomes faster
Many problems (including LCA) become easier
Understanding this rule is the key to solving the LCA problem efficiently.
What is the Lowest Common Ancestor?
The Lowest Common Ancestor of two nodes p and q is defined as:
The lowest node in the tree that has both
pandqas its descendants.
Important points to understand clearly:
A node can be a descendant of itself
The LCA is always unique
The LCA does not have to be the root
Real-Life Example to Understand LCA
Think of a family tree:
Two cousins meet at their grandparent
Two siblings meet at their parent
That meeting point is similar to the Lowest Common Ancestor in a tree.
Example Tree
Consider the following BST:
6
/ \
2 8
/ \ / \
0 4 7 9
/ \
3 5
If:
p = 2 and q = 8 → LCA = 6
p = 2 and q = 4 → LCA = 2
p = 3 and q = 5 → LCA = 4
Why BST Property Makes LCA Easy
In a normal binary tree, finding LCA requires extra work.
But in a BST, values guide us:
If both values are smaller than current node → move left
If both values are greater than current node → move right
If values lie on different sides → current node is LCA
This reduces unnecessary traversal.
Detailed Step-by-Step Explanation
Let current node be root.
Compare values of
pandqwithrootIf both are smaller than
root, search in left subtreeIf both are greater than
root, search in right subtreeIf one is smaller and the other is larger,
rootis the LCAStop traversal once LCA is found
This logic works because BST values are ordered.
Detailed Dry Run Example
Let p = 2 and q = 8
| Current Node | p < node | q > node | Decision |
|---|---|---|---|
| 6 | Yes | Yes | LCA found |
Answer = 6
Another example:
Let p = 3 and q = 5
Join the conversation! Your thoughts help the community grow.