Learn / Trees

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

351620874
The lowest common ancestor of 7 and 4 is 2; of 6 and 4 it is 5; of 5 and 1 it is 3.
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

QuestionMethod
distance between a and bfind the LCA, then add the depths of a and b below it
kth ancestor of a noderecord the path from the root to it; read k places from the end
LCA in a BSTwalk 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

0 of 3 solved

Check yourself

In the pictured tree, what is the LCA of 6 and 4?

Can a node be its own ancestor in this definition?

The distance between a and b equals?