Video in progress
How do you find the lowest common ancestor (LCA) of two nodes in a binary tree?
Postorder DFS: look at what comes back from the left and right subtrees. If a node comes back from both, the current node is the LCA. If it comes back from only one, we pass that up. O(n) time, O(h) stack.
📖 Answer
TreeNode lca(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
TreeNode left = lca(root.left, p, q);
TreeNode right = lca(root.right, p, q);
if (left != null && right != null) return root; // p and q are on both sides
return left != null ? left : right;
}
The function returns "p or q, whichever is in this subtree, or their LCA". The first node that gets something from both sides is the answer.
This code has a hidden assumption: p and q are definitely in the tree. If q is missing, the function returns p and you'd think "LCA found". In an interview you should state this assumption openly, or verify that both were found with a separate counter.
If the tree is a BST, it's much easier: if both values are smaller than the current node, go left; if both are larger, go right; otherwise this node is the answer. It's O(h) and can be written without recursion.
If the nodes have a parent pointer, the problem turns into "the intersection point of two linked lists".
With many queries (say a million "common manager of two employees" lookups in an org hierarchy), O(n) each time is expensive. With binary lifting, after a one-time O(n log n) preparation, each query is O(log n).
Sign up to mark studied questions and save your progress.