sangonm
sangonm

Reputation: 11

Binary tree giving "TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'"

I' trying to implement a method to a binary tree that give me the total sum of all the elements of the tree:

def totalsumprint(self): print("The tree's value's total sum:") self.totalsum(self.root)

def totalsum(self, node):
    if node:
        return node.value + self.totalsum(node.left) + self.totalsum(node.right)

This is what I currently have, but its giving me this error "TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'", can someone help me figuring this up? Thank

Upvotes: 0

Views: 79

Answers (1)

ProfDFrancis
ProfDFrancis

Reputation: 9411

Try ensuring the function returns a zero, rather than None, if node is None

def totalsum(self, node):
    if node:
        return node.value + self.totalsum(node.left) + self.totalsum(node.right)
    else:
        return 0

Upvotes: 0

Related Questions