0
因此,我正在努力編寫一個遞歸方法來查找樹的高度。這個每個樹節點都有一個孩子列表。我的代碼返回異常,因爲max
莫名其妙是一個空序列。有人可以提供一個有效的嗎?如何找到非二叉樹的高度?
def height(t):
"""
Return 1 + length of longest path of t.
@param Tree t: tree to find height of
@rtype: int
>>> t = Tree(13)
>>> height(t)
1
>>> t = descendants_from_list(Tree(13), [0, 1, 3, 5, 7, 9, 11, 13], 3)
>>> height(t)
3
"""
# 1 more edge than the maximum height of a child, except
# what do we do if there are no children?
if t.children is None:
return 1
else:
return 1+max(height(x) for x in t.children)
解決您的壓痕請:) – Torxed