Search code examples
pythonbinary-treenonetype

Summing nodes in binary tree (python) - TypeError: 'NoneType'


I am trying to sum up the nodes in a binary tree:

def average(tree):
   if tree is None:
       return
   total = (tree['data']) + (average(tree['left'])) + (average(tree['right']))
   print(total)

I also tried with "is" and "is not" however it still gave me the following error:

 TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Solution

  • There are two issues here which have to do with taking care to return values once they have been calculated from average.

    First, in your code the lone return statement will return the non-numeric None value. This is an issue as when you get any node without two child nodes (e.g. a leaf), tree['left'] or/and tree['right'] will return None. This None is passed to average, which returns None back. The error you are getting is due to subsequenly trying to add this returned value on the 3rd line of the function. To fix this, you can simply return a "base case" value for what should the "average" of a tree that is empty be.

    Second, even in the case where average is called recursively on a child node that is not None, average will still return None because as there is no other return statement in the function, and in Python when evaluation reaches the end of a function without a return statement there is an implicit return of None. To fix this simply return the total that you have calculated!

    Fixing these two problems might look like the following:

    def average(tree):
       if tree is None:
           return 0
       total = tree['data'] + average(tree['left']) + average(tree['right'])
       return total
    

    although I can't say for certain that returning zero in the base case is the best for exactly what you are trying to accomplish.

    As a final note, you may want to add a check that tree['data'] is not None to rule out edge cases where nodes have no data!