【问题标题】:Return the depth of the deepest node in a tree返回树中最深节点的深度
【发布时间】:2015-07-15 00:31:22
【问题描述】:

这是我解决这个问题的代码

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')

【问题讨论】:

  • 树形输入示例?
  • @heinst height(tree(1, [tree(2), tree(3)]))
  • 因为你没有关闭评论,

标签: python algorithm list tree


【解决方案1】:

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

因为你的height 函数是错误的。 height 函数甚至没有调用 entrysubtrees 函数。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2021-10-04
    • 2020-07-19
    • 2015-05-04
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多