在不使用列表的情况下查找树的高度

时间:2015-03-23 22:51:17

标签: python recursion tree height

def height(t):
''' (Tree) -> int

Return 1 + the number of nodes in longest path in Tree t.

>>> tree = Tree(23)
>>> height(Tree)
1
>>> tree = descendents_from_list(Tree(11), [2, 3, 4, 5, 6], 3)
>>> height(tree)
3
'''
num = 1
for i in t.children:
    if i.children:
       num += height(i)
return num

对于带有t.value和t.children的上述函数,我需要弄清楚如何在不使用列表的情况下找到高度。就像我需要找到一种方法来递归地进入树下而不跟踪父树。

我已经尝试过了,但我无法弄明白。有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

基本思想是,树的高度由树中最长的路径决定。因此,如果我们正在查看具有子节点的节点,任何节点,我们要注意哪个子节点的高度? 最高高度的子节点,对吗?在Python中,我们可以使用内置的max函数获得任何可迭代值集的最高值。在整个过程中的每一点,我们都想在所有子树中加上1到最大高度。

所以现在我们只需要递归的基本情况,即如果节点没有子节点我们该怎么办?只需返回1.

以下代码说明了此算法:

def height(t):
    if not t.children:
        return 1
    else:
        return max(height(c) for c in t.children) + 1

答案 1 :(得分:0)

你能为这个创建一个函数吗

num = 1
def height(t):
    global num
    child = [i for i in t if i.children]
    if child:
        num += 1
        height(child) #reccursing
    else:
        return num
相关问题