Topics / Data Structures & Algorithms / Q26
Find the lowest common ancestor of two nodes in a binary tree.
Short answer: Search both subtrees. If one target appears on each side, the current node is their lowest common ancestor.
struct tree {
int key;
struct tree *left, *right;
};
struct tree *lca(struct tree *r, struct tree *a,
struct tree *b)
{
if (!r || r == a || r == b) return r;
struct tree *l = lca(r->left, a, b);
struct tree *t = lca(r->right, a, b);
if (l && t) return r;
return l ? l : t;
}
Assume both target nodes exist in the tree; otherwise verify membership first. For root 8 with children 3 and 12, their LCA is 8. Time O(n), space O(h). In a BST with unique keys, compare both keys to the current key and descend only when both are on the same side, taking O(h) time.