如何求和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
答案 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
是单身人士。