2016-03-10 60 views
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) 
+1

解決您的壓痕請:) – Torxed

回答

2

我猜t.children列表 - [] - 葉節點,不None

>>> [] is None 
False 
>>> not [] 
True 

max不能空iterables使用 - 你怎麼想象將是[],0或-∞,或42的最大價值?

if not t.children:只是測試:

if not t.children: 
    return 1 

else: 
    return 1 + max(height(x) for x in t.children) 
+0

+1幫我弄清楚如何計算spaCy依賴解析的解析樹的高度。 (在這裏評論,所以人們可以通過搜索這些條款來找到這個q/a。 –