LeetCode 题解工作台
树节点的第 K 个祖先
给你一棵树,树上有 n 个节点,按从 0 到 n-1 编号。树以父节点数组的形式给出,其中 parent[i] 是节点 i 的父节点。树的根节点是编号为 0 的节点。 树节点的第 k 个祖先节点是从该节点到根节点路径上的第 k 个节点。 实现 TreeAncestor 类: TreeAncestor…
6
题型
6
代码语言
3
相关题
当前训练重点
困难 · 二分·树·traversal
答案摘要
题目要我们寻找节点 的第 个祖先节点,如果暴力求解,需要从 开始向上遍历 次,时间复杂度为 ,显然会超时。 我们可以使用动态规划,结合倍增的思想来处理。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一棵树,树上有 n 个节点,按从 0 到 n-1 编号。树以父节点数组的形式给出,其中 parent[i] 是节点 i 的父节点。树的根节点是编号为 0 的节点。
树节点的第 k 个祖先节点是从该节点到根节点路径上的第 k 个节点。
实现 TreeAncestor 类:
TreeAncestor(int n, int[] parent)对树和父数组中的节点数初始化对象。getKthAncestor(int node, int k)返回节点node的第k个祖先节点。如果不存在这样的祖先节点,返回-1。
示例 1:

输入: ["TreeAncestor","getKthAncestor","getKthAncestor","getKthAncestor"] [[7,[-1,0,0,1,1,2,2]],[3,1],[5,2],[6,3]] 输出: [null,1,0,-1] 解释: TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]); treeAncestor.getKthAncestor(3, 1); // 返回 1 ,它是 3 的父节点 treeAncestor.getKthAncestor(5, 2); // 返回 0 ,它是 5 的祖父节点 treeAncestor.getKthAncestor(6, 3); // 返回 -1 因为不存在满足要求的祖先节点
提示:
1 <= k <= n <= 5 * 104parent[0] == -1表示编号为0的节点是根节点。- 对于所有的
0 < i < n,0 <= parent[i] < n总成立 0 <= node < n- 至多查询
5 * 104次
解题思路
方法一:动态规划 + 倍增
题目要我们寻找节点 的第 个祖先节点,如果暴力求解,需要从 开始向上遍历 次,时间复杂度为 ,显然会超时。
我们可以使用动态规划,结合倍增的思想来处理。
我们定义 表示节点 的第 个祖先节点,即 表示节点 向上走 步的节点。那么我们可以得到状态转移方程:
即:要想找到节点 的第 个祖先节点,我们可以先找到节点 的第 个祖先节点,然后再找到该节点的第 个祖先节点即可。所以,我们要找到每个节点的距离为 的祖先节点,直到达到树的最大高度。
之后对于每次查询,我们可以把 拆成二进制的表示形式,然后根据二进制中 的位置,累计向上查询,最终得到节点 的第 个祖先节点。
时间复杂度方面,初始化为 ,查询为 。空间复杂度 。其中 为树的节点数。
相似题目:
class TreeAncestor:
def __init__(self, n: int, parent: List[int]):
self.p = [[-1] * 18 for _ in range(n)]
for i, fa in enumerate(parent):
self.p[i][0] = fa
for j in range(1, 18):
for i in range(n):
if self.p[i][j - 1] == -1:
continue
self.p[i][j] = self.p[self.p[i][j - 1]][j - 1]
def getKthAncestor(self, node: int, k: int) -> int:
for i in range(17, -1, -1):
if k >> i & 1:
node = self.p[node][i]
if node == -1:
break
return node
# Your TreeAncestor object will be instantiated and called as such:
# obj = TreeAncestor(n, parent)
# param_1 = obj.getKthAncestor(node,k)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate uses binary lifting or another logarithmic ancestor retrieval method.
- question_mark
Listen for explanations on how state propagation in the tree avoids redundant traversal.
- question_mark
Watch for awareness of edge cases when k exceeds the node's depth.
常见陷阱
外企场景- error
Attempting to traverse up k steps linearly for each query, causing time limit exceeded errors.
- error
Not initializing ancestor table correctly, leading to incorrect returns for nodes near the root.
- error
Ignoring the binary representation approach, missing the opportunity for logarithmic query optimization.
进阶变体
外企场景- arrow_right_alt
Compute the lowest common ancestor (LCA) for multiple pairs of nodes using similar binary lifting preprocessing.
- arrow_right_alt
Determine the distance between any two nodes efficiently using ancestor jumps.
- arrow_right_alt
Support dynamic tree modifications with online ancestor queries, requiring updated state propagation.