【发布时间】:2019-07-19 03:08:53
【问题描述】:
我想解决关于获取树高的 cousera 作业。它要求我使用递归函数获取高度。我写了这个函数,但我仍然没有得到。第一行的输入是节点的数量,第二行是一个数字列表,每个数字都指向该节点的父节点的索引(-1 值表示该节点是根节点)。
我尝试打印max_height,它给了我一个数字列表。当我调试它时,我看到它首先作为例外工作,但在流程返回时,值会在中间发生变化。
def compute_height(n, parents, postion=0, hight=0, max_hight=0, current=0):
if postion == n-1:
print(max_hight)
return max_hight
if current != -1:
compute_height(n, parents, postion, hight+1,
max(max_hight, hight), parents[current])
compute_height(n, parents, postion+1, 0, max_hight, postion+1)
它返回None。我该如何解决这个问题?
【问题讨论】:
-
输入和预期输出是什么?
-
第一行:5,第二行:4 -1 4 1 1 输出(应该):3
标签: python python-3.x recursion tree