user6116345
user6116345

Reputation: 23

error in sum the value in binary search tree

How can I sum the values that inside bst (binary search tree) I tried this code but gave me error

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

the error that I get it:

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

Also, I tried this way it gives me zero

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

Upvotes: 1

Views: 78

Answers (1)

mgilson
mgilson

Reputation: 309899

Maybe you want an 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

As your code is written, if node == None, then you set total = 0 and immediately go on the check node._right (which doesn't exist because None doesn't have a _right attribute)


Also, as an aside, if node is None is generally preferred to if node == None since None is a singleton.

Upvotes: 1

Related Questions