Kth Ancestor of a Tree Node Problem
Description
LeetCode Problem 1483.
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of i^th node. The root of the tree is node 0. Find the k^th ancestor of a given node.
The k^th ancestor of a tree node is the k^th node in the path from that node to the root node.
Implement the TreeAncestor class:
TreeAncestor(int n, int[] parent)Initializes the object with the number of nodes in the tree and the parent array.int getKthAncestor(int node, int k)return thek^thancestor of the given nodenode. If there is no such ancestor, return-1.
Example 1:

Input
["TreeAncestor", "getKthAncestor", "getKthAncestor", "getKthAncestor"]
[[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]
Output
[null, 1, 0, -1]
Explanation
TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);
treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3
treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5
treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor
Constraints:
1 <= k <= n <= 5 * 10^4parent.length == nparent[0] == -10 <= parent[i] < nfor all0 < i < n0 <= node < n- There will be at most
5 * 10^4queries.
Solution
Approach: Binary Lifting
Walking up one parent at a time costs O(k) per query, which is too slow for 5 * 10^4 queries on a tree that can be a long chain.
Binary lifting precomputes jumps of length 1, 2, 4, 8, .... Let up[j][i] be the 2^j-th ancestor of node i (or -1 if it does not exist):
up[0][i] = parent[i];up[j][i] = up[j - 1][ up[j - 1][i] ]: jumping2^jlevels is jumping2^(j-1)levels twice. If the first half already leaves the tree, the result is-1.
Since k <= 5 * 10^4 < 2^16, 16 levels of jumps are enough.
To answer getKthAncestor(node, k), write k in binary and, for each set bit j, jump up[j][node]. For example, k = 13 = 8 + 4 + 1 takes three jumps. The order of the jumps does not matter, since they all go up the same path. If a jump reaches -1, the node does not have that many ancestors and we stop.
Complexity: O(n log n) time and space to build the table, and O(log k) per query.
class TreeAncestor:
LOG = 16 # 2^16 > 5 * 10^4, the largest possible k
def __init__(self, n: int, parent: List[int]):
# up[j][i]: the 2^j-th ancestor of i, or -1
self.up = [parent[:]]
for j in range(1, self.LOG):
prev = self.up[j - 1]
self.up.append([-1 if prev[i] == -1 else prev[prev[i]] for i in range(n)])
def getKthAncestor(self, node: int, k: int) -> int:
j = 0
while k and node != -1:
if k & 1: # jump 2^j levels for each set bit of k
node = self.up[j][node] if j < self.LOG else -1
k >>= 1
j += 1
return node