在Python中返回有序树中节点的高度

时间:2015-10-21 23:59:48

标签: python tree nodes

我是Python的新手,我试图在python中返回有序树中节点的高度。这是我的代码:

def Height(node, T):
    if Is_OrdLeaf(T) and node == OrdRoot(T):
        return 0
    else:
        heights = []
        for x in Children(node, T):
            heights += [Height(x, T) + 1]
        return max(heights)

但是,当我用树运行此代码时,我得到了

  

ValueError:max()arg是一个空序列

所有被调用的函数都有效,因此,高度不应为空。怎么了?

提前致谢

2 个答案:

答案 0 :(得分:0)

heights = []

def height(t, level=0):
    if not t.children:
        heights.append(level)
    else:
        for c in t.children:
            height(c, level+1) 
    return max(heights)

答案 1 :(得分:0)

我很想为你测试一下,但你省略了树类。它是某种标准包装吗?

else:
    return max([Height(x, T) for x in Children(node, T)])

如果您有一棵大树,用生成器理解替换列表可能会更好(将括号更改为括号)。