# Sum of binary tree leaves' values

2 views

I wrote this code and when I use print I see that I get the leaves. However, the final return from the function is None and not the sum of the leaves, which is supposed to be 7 in this example. I'd be happy to know whats wrong here.

class Node:

def __init__(self, val=None):

self.left = None

self.right = None

self.val = val

def sum_leafs(tree):

if tree is None:

return 0

if tree.right and tree.left:

sum_leafs(tree.right)

sum_leafs(tree.left)

elif tree.right or tree.left:

if tree.right:

sum_leafs(tree.right)

elif tree.left:

sum_leafs(tree.left)

elif tree.right is None and tree.left is None:

return sum_leafs(tree.left) + 1

node = Node(10)

node.right = Node(2)

node.left = Node(11)

node.left.right = Node(5)

print(sum_leafs(node))

by (25.1k points)

You did not use the addition operator to add the values of the tree nodes also you have not use the val member of the nodes. You can do it by simple recursion

def sum_leafs(node):

if node is None:

return 0

if not node.right and not node.left:

return node.val

return sum_leafs(node.right) + sum_leafs(node.left)