Binary Lifting
Both problems ask you to climb from a node toward the root, and to do it for
many queries. The only move the tree gives you is "go to the parent", so a
climb of k steps costs k steps, every query.
Binary lifting is the fix for the first one: write k in binary, and climb by
jumps of 2j instead. Precompute up[j][v], the 2jth ancestor of v,
once. Then any climb is at most log n jumps, one per set bit of k.
The table builds itself, because a jump of 2j is two jumps of 2j-1:
The jump table is needed only for 1483. The second problem gets its climb for free from the heap labels, as shown below.
The hub: an explicit parent array
parent arrayA tree as a parent array, and queries that each climb k steps.
The first solution just walks up, and it is the baseline: O(k) per query.
The second is the table above. Build it row by row, then read the bits of k
from the lowest and take the up[j] jump wherever bit j is set. Build costs
O(n log n), and every query after that costs O(log n). Because -1 maps to
-1, a climb that falls off the root needs no special case. That cost is the
trade: a table you only get to amortise over many queries.
1483. Kth Ancestor of a Tree Node
1483. Kth Ancestor of a Tree Node
Walk Up
The same climb, no table
1483 with the parent link built into the labels. The tree is never given:
node v has children 2v and 2v + 1, so its parent is v >> 1.
The cycle is the path between the two nodes plus the new edge, so the work is finding where the two climbs meet. This is the same question as the Lowest Common Ancestor page, and the last solution, Halve the Larger Label, answers it by always shifting the larger label, since the deeper node always has the bigger one.
It does not need a table. A node here is at most n shifts from the root, so
a single step at a time is already cheap, and storing jumps would cost more
than it saves. Binary lifting pays off when the climbs are long and the parent
is something you must look up. Where the parent is a free shift, you skip it.
2509. Cycle Length Queries in a Tree
2509. Cycle Length Queries in a Tree
DFS (Recursive, Full Walk)
The two problems side by side:
| Problem | Parent link | Jump size | Per query | Extra memory |
|---|---|---|---|---|
| 1483 Kth Ancestor of a Tree Nodethe hub | parent[v] | 2jfrom a precomputed table | O(log n) | O(n log n)the jump table |
| 2509 Cycle Length Queries in a Treefrom 1483 | label >> 1 | 1one shift per step | O(n)n is the number of levels | O(1) |