2016-03-26 57 views
1

我如何總結這裏面BST(二叉搜索樹) 我嘗試這個代碼,但給的值Me錯誤誤差總和二叉搜索樹

def total(bst): 
    total = 0 
    bst = BST() 
    node = bst._root 
    if node == None: 
     total = 0 
    if node._right is not None and node._left is not None: 
     total = total + node._right + node._left 
    elif node._right is not None and node._left is None: 
     total = total + node._right 
    else: 
     total = total + node._left 
    return total 

,我得到它的誤差值:

if node._right is not None and node._left is not None: 
AttributeError: 'NoneType' object has no attribute '_right' 

而且,我想這種方式給了我零

bst.comparision = 0 
x= bst.comparision 
return x 

回答

1

也許你想要一個elif

def total(bst): 
    total = 0 
    bst = BST() 
    node = bst._root 
    if node == None: 
     total = 0 
    # elif, not if? 
    elif node._right is not None and node._left is not None: 
     total = total + node._right + node._left 
    elif node._right is not None and node._left is None: 
     total = total + node._right 
    else: 
     total = total + node._left 
    return total 

當你的代碼編寫,如果node == None,然後設置total = 0並立即去檢查node._right(不因爲None存在不具有_right屬性)


此外,順便說一下,if node is None通常優於if node == None,因爲None是單身人士。

+0

我這樣做,但給我零! – user6116345