返回树中最深节点的深度

时间:2015-07-15 00:31:23

标签: python algorithm list tree

这是我的问题代码

def height(t):
"""Return the depth of the deepest node in the tree."""
if isinstance(t, list):
    t = t[1:]
    if t != empty:
        return 1 + max([height(x) for x in t])
return 0

但它没有像我预期的那样返回值。有人能搞清楚吗? 谢谢。 我的树方法是:

def tree(entry, subtrees=[]):
    return lambda dispatch: entry if dispatch == 'entry' else list(subtrees)
def entry(tree):
    return tree('entry')
def subtrees(tree):
    return tree('subtrees')

1 个答案:

答案 0 :(得分:0)

height函数的参数应该是一个树,但是你希望它是一个列表if isinstance(t, list),显然它不是列表,所以只返回0.

因为您的height功能错误。 height函数甚至没有调用entrysubtrees函数。

应该得到树的子树,如果是空的,那么返回1.如果不为空,则返回1 + t的子树高度的最大值。

我不粘贴代码,请自行检查。

相关问题