Graph Theory37 sections · 1633 units
Open in Course

Core Idea - Query Method

(Return -1 if out of bounds)

The getKthAncestor(node,k)getKthAncestor(node, k) method should return the kk-th ancestor, or 1-1 if it does not exist. Use the same binary decomposition loop. If at any point node becomes 1-1 (past the root), return 1-1. Otherwise, after the loop, return the final node. Time: O(logk)O(\log k) per query.

In the worst case, k=nk = n, so queries take O(logn)O(\log n). The method body is just a few lines: a loop over bits of kk with jumps through the upup table.