Graph Theory37 sections · 1633 units
Open in Course

The k-th Ancestor Problem

(Find ancestor k steps up)

Given a tree and a node vv, who is the kk-th ancestor of vv?

The kk-th ancestor is the node you reach by going up kk steps toward the root. For example, if vv has parent pp, then pp is the 11st ancestor. The parent of pp is the 22nd ancestor. The root is the depth[v]-th ancestor.

The naive approach jumps one parent at a time, taking O(k)O(k) per query. If kk is close to nn and you have qq queries, that is O(nq)O(nq) total.