Graph Theory37 sections · 1633 units
Open in Course

Algorithm

Preprocess then query

1.1. Read the tree, build parent array.

2.2. Build the upup table:

up[v][0] = parent[v]

up[v][j] = up[up[v][j-1]][j-1]

3.3. For each query (v,k)(v, k), jump up kk steps using the binary lifting technique.

4.4. If you reach an invalid node (null or past root), return 1-1.

Otherwise, return the final node.

This runs in O(nlogn)O(n \log n) preprocessing time and O(logn)O(\log n) per query. Space is O(nlogn)O(n \log n) for the table.