Graph Theory37 sections · 1633 units
Open in Course

Core Idea - Handling Invalid Queries

(When k exceeds depth)

If kk is larger than the depth of vv, there is no kk-th ancestor. You will jump past the root. Handle this by checking if vv becomes 1-1 or null during the jumps.

If so, return 1-1. Alternatively, compute depth and check k > depth[v] before jumping. Either approach works. The jumping method is simpler because you do not need to precompute depths separately. If up[root][0] = root, you will stay at root forever, so also check if you have jumped more times than needed.