【发布时间】:2016-06-24 02:03:43
【问题描述】:
我正在尝试实现一种递归方法来确定任意树的树高,而不是二叉树。我们有两个输入,一个是“n”个顶点数。第二行包含 n 个整数 从 -1 到 n - 1 个顶点的父节点。如果其中第 i 个 (0 ≤ i ≤ n − 1) 为 -1,则顶点 i 为根,否则为第 i 个顶点的父节点的从 0 开始的索引。保证只有一个根。保证输入代表一棵树。
例如输入是: n = 5 父级 = [4, -1, 4, 1, 1] 这意味着节点 0 是节点 4 的子节点,节点 1 是根节点,节点 2 是节点 4 的子节点,节点 3 是节点 1(根)的子节点,节点 4 同样是节点 1 的子节点根。自:
0 1 2 3 4
4 -1 4 1 1
输出将是树的高度为 3。我们得到了一个慢速方法,任务是实现一个更快的方法。恐怕我看不到如何将节点输入输入到以下内容:
Height(tree)
if tree = null:
return 0
else:
return 1 + Max(Height(tree.child))
# I realise this is a max of one value
提前致谢!
# python3
import sys, threading
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
n = 5
parent = [4, -1, 4, 1, 1]
class TreeHeight:
def read(self, n, parent):
self.n = n
self.parent = parent
def compute_height(self):
# Replace this code with a faster implementation
maxHeight = 0
for vertex in range(self.n):
height = 0
i = vertex
while i != -1:
height += 1
i = self.parent[i]
maxHeight = max(maxHeight, height);
return maxHeight;
def main():
tree = TreeHeight()
tree.read(n, parent)
print(tree.compute_height())
threading.Thread(target=main).start()
【问题讨论】:
标签: python algorithm recursion tree