Lowest common ancestor
The lowest common ancestor of two nodes is the deepest node that has both below it (a node counts as below itself). Recurse: return the node if it is one of the two; if both subtrees return something, this node is the answer; otherwise pass up whichever side found something. Distances between nodes and kth ancestors follow from the same paths.
How to recognise it
- Two nodes, and the question is where their paths meet.
- The distance between two nodes of a tree.
- An ancestor a given number of levels up.
The picture
lca(n, p, q):
if n is null or n is p or n is q: return n
l = lca(n.left, p, q); r = lca(n.right, p, q)
if l and r: return n # one on each side
return l or r
What a node, a child, a leaf and a level are is on the Structures page.
Using it
| Question | Method |
|---|---|
| distance between a and b | find the LCA, then add the depths of a and b below it |
| kth ancestor of a node | record the path from the root to it; read k places from the end |
| LCA in a BST | walk down: both smaller go left, both larger go right, otherwise stop |
Common mistakes
- Assuming both nodes exist when the problem does not promise it.
- Comparing values instead of nodes when values can repeat.
Problems
- Lowest Common Ancestor of a Binary Treemediumguide ready
- Find distance between 2 nodes in a Binary treemediumguide ready
- Kth Ancestor of node in a Binary treemediumguide ready