Find the lowest common ancestor of two nodes in a binary tree (and in a BST).
Problem
Given two nodes p and q, return the deepest node that has both as descendants (a node can be its own descendant).
Approach
- Binary tree: recurse; if the current node is null, p or q, return it. Otherwise search both subtrees. If both sides return non-null, the current node is the LCA; otherwise pass up the non-null side.
- Binary search tree: use the ordering: if both values are smaller than the node go left, if both are larger go right, otherwise this node is the split point. Iterative, O(h).
class LowestCommonAncestor {
static final class Node {
final int val;
Node left, right;
Node(int val) { this.val = val; }
}
static Node lcaBinaryTree(Node root, Node p, Node q) {
if (root == null || root == p || root == q) return root;
Node left = lcaBinaryTree(root.left, p, q);
Node right = lcaBinaryTree(root.right, p, q);
if (left != null && right != null) return root; // p and q are on different sides
return left != null ? left : right;
}
static Node lcaBst(Node root, int p, int q) {
Node node = root;
while (node != null) {
if (p < node.val && q < node.val) node = node.left;
else if (p > node.val && q > node.val) node = node.right;
else return node; // split point
}
return null;
}
public static void main(String[] args) {
// 6
// / \
// 2 8
// / \ / \
// 0 4 7 9
Node root = new Node(6);
root.left = new Node(2); root.right = new Node(8);
root.left.left = new Node(0); root.left.right = new Node(4);
root.right.left = new Node(7); root.right.right = new Node(9);
System.out.println(lcaBst(root, 2, 8).val); // 6
System.out.println(lcaBst(root, 2, 4).val); // 2
System.out.println(lcaBinaryTree(root, root.left.left, root.left.right).val); // 2
}
}Complexity
Binary tree: O(n) time, O(h) stack. BST: O(h) time, O(1) space.
Follow-up questions interviewers ask
Try answering each one before you open it.
What if p or q might not be in the tree?
The basic recursion would wrongly return p when q is absent. Track whether each node was actually found (return flags or counts from the recursion) and only return the LCA if both were found. Alternatively, verify both exist with a separate search first.
How would you answer many LCA queries on a large, static tree quickly?
Preprocess with binary lifting: store each node's 2^i-th ancestor and its depth (O(n log n) time and space), then answer each query in O(log n) by lifting the deeper node to the same depth and jumping both up while their ancestors differ. Euler tour plus a sparse-table RMQ gives O(1) queries.