Lowest Common Ancestor of a Binary Search Tree (LeetCode 235): Solution and Explanation
Given a binary search tree and two nodes p and q that are both in it, find their lowest common ancestor. That is the deepest node that has both p and q as descendants, where a node is allowed to be a descendant of itself.
Watch it run step by step
Try your own input and write the code →Intuition
In a general binary tree you would have to search both subtrees to learn where p and q live. A binary search tree gives you that information for free. Every value smaller than a node sits in its left subtree and every larger value sits in its right subtree, so comparing p.val and q.val with the current node tells you exactly which side each target is on.
Start at the root, which is a common ancestor of everything. If both targets are larger than the current value, they both live in the right subtree, so the right child is also a common ancestor and a deeper one. If both are smaller, the same reasoning sends you left. Keep stepping down while both targets agree on a direction.
The moment they disagree, you have found the answer. Either one target is on the left and the other on the right, so the current node is the last place their paths overlap, or one target equals the current node, in which case it is an ancestor of the other. In both cases no deeper node can contain both, so the current node is the lowest common ancestor.
Approach: Iterative descent using BST ordering
- Set
curto the root of the tree. - If both
p.valandq.valare greater thancur.val, movecurtocur.right. - Else if both values are less than
cur.val, movecurtocur.left. - Otherwise the targets split here, or one of them equals
cur, so returncuras the lowest common ancestor. - Repeat until a node is returned. Because both nodes are guaranteed to exist, the loop always returns before
curbecomes None.
Step-by-step example
root = [6,2,8,0,4,7,9,null,null,3,5], p = 3, q = 5
- Start at 6. Both 3 and 5 are less than 6, so move left to 2.
- At 2, both 3 and 5 are greater than 2, so move right to 4.
- At 4, 3 is smaller and 5 is larger, so the targets split. Return node 4.
- Node 4 is the parent of both 3 and 5, and no deeper node contains both, so the answer is 4.
- With p = 2 and q = 4 instead, the walk would move from 6 to 2 and stop there, because 2 equals
p, returning 2.
Code: Python, Java, C++
1class Solution:
2 def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
3 cur = root
4
5 while cur:
6 if p.val > cur.val and q.val > cur.val:
7 cur = cur.right
8 elif p.val < cur.val and q.val < cur.val:
9 cur = cur.left
10 else:
11 return cur1class Solution {
2 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
3 TreeNode cur = root;
4
5 while (cur != null) {
6 if (p.val > cur.val && q.val > cur.val) {
7 cur = cur.right;
8 } else if (p.val < cur.val && q.val < cur.val) {
9 cur = cur.left;
10 } else {
11 return cur;
12 }
13 }
14 return null;
15 }
16}1class Solution {
2public:
3 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
4 TreeNode* cur = root;
5
6 while (cur) {
7 if (p->val > cur->val && q->val > cur->val) {
8 cur = cur->right;
9 } else if (p->val < cur->val && q->val < cur->val) {
10 cur = cur->left;
11 } else {
12 return cur;
13 }
14 }
15 return nullptr;
16 }
17};Time and space complexity
O(h)
Each iteration moves one level down, and the walk follows a single root-to-node path, so it takes at most h steps where h is the tree height. That is O(log n) for a balanced tree and O(n) for a skewed one.
O(1)
The loop keeps only the cur pointer. There is no recursion stack or auxiliary structure.
Other approaches
Recursive descent (time O(h), space O(h))
The same comparison logic written recursively: recurse right if both values are larger, left if both are smaller, otherwise return the current node. It reads naturally but uses O(h) stack space.
General binary tree LCA (time O(n), space O(h))
Ignore the BST property and use the postorder search that returns a node when it finds p or q in both subtrees. It works but visits up to every node, which wastes the ordering information.
Common mistakes
- Using
>=or<=in the direction checks. If one target equalscur.val, you must stop and returncur, not keep descending past it. - Comparing node objects instead of their values, which breaks the ordering logic.
- Falling back to the general binary tree algorithm and visiting the whole tree, which turns an O(h) problem into O(n).
- Assuming
p.valis smaller thanq.val. The conditions must check both values againstcurwithout relying on their order.
Frequently asked questions
Why is the LCA in a BST found in O(h) time?
The ordering property tells you which subtree contains each target, so you only follow one path from the root downward. That path is at most as long as the tree's height.
Can a node be its own lowest common ancestor?
Yes. A node counts as a descendant of itself, so if p is an ancestor of q, then p is the answer. The algorithm handles this because the direction checks fail when cur equals one of the targets.
How is this different from LCA in a regular binary tree?
A regular binary tree has no ordering, so you must search both subtrees and combine the results, which is O(n). In a BST you can decide the direction with a comparison and walk a single path.