【发布时间】:2020-06-14 05:25:30
【问题描述】:
挑战如下:
给你一棵树,它有 n 个节点,编号从 0 到 n-1,形式为 parent 数组,其中 parent[i] 是节点 i 的父节点。树的根 是节点 0。
实现函数getKthAncestor(int node, int k)返回第k个 给定节点的祖先。如果没有这样的祖先,则返回-1。
树节点的第 k 个祖先是该路径中的第 k 个节点 节点到根。
例子:
输入:
["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); // 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
约束:
1 <= k <= n <= 5*10^4
parent[0] == -1 indicating that 0 is the root node.
0 <= parent[i] < n for all 0 < i < n
0 <= node < n
There will be at most 5*10^4 queries.
我很难理解一个人对此的解决方案。有人愿意解释他的最佳解决方案是如何工作的吗?这是一个新的挑战,在最近的 leetcode 竞赛中,没有重复。
class TreeAncestor(object):
def __init__(self, n, parent):
self.pars = [parent]
self.n = n
for k in range(17):
row = []
for i in range(n):
p = self.pars[-1][i]
if p != -1:
p = self.pars[-1][p]
row.append(p)
self.pars.append(row)
def getKthAncestor(self, node, k):
"""
:type node: int
:type k: int
:rtype: int
"""
i = 0
while k:
if node == -1: break
if (k&1):
node = self.pars[i][node]
i += 1
k >>= 1
return node
【问题讨论】:
-
这是一个众所周知的问题,解决方案使用稀疏表和二进制提升,an example
标签: python python-3.x tree dynamic-programming