方法:倍增法dp ACM经典
class TreeAncestor: def __init__(self, n: int, parent: List[int]): self.cols = 20 # log(50000) < 20 self.dp = [[-1] * self.cols for _ in range(n)] for i in range(n): self.dp[i][0] = parent[i] # 动态规划设置祖先, dp[node][j] 表示 node 往前推第 2^j 个祖先 for j in range(1, self.cols): for i in range(n): if self.dp[i][j-1] != -1: self.dp[i][j] = self.dp[self.dp[i][j-1]][j-1] return def getKthAncestor(self, node: int, k: int) -> int: for i in range(self.cols - 1, -1, -1): if k & (1 << i): node = self.dp[node][i] if node == -1: break return node
原文:https://www.cnblogs.com/oldby/p/13155373.html