将二进制搜索树中的值相加得出的错误

时间:2016-03-26 05:14:06

标签: python binary-search-tree

如何求和bst内的值(二叉搜索树) 我试过这段代码但是给了我错误

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 个答案:

答案 0 :(得分: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没有&{ #39; t有_right属性)

另外,if node is None通常优先于if node == None,因为None是单身人士。