Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
by (19.9k points)

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:



    elif tree.right or tree.left:

        if tree.right:


        elif 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)


1 Answer

0 votes
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)

Related questions

0 votes
1 answer
asked Feb 9, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Jan 6, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Aug 27, 2019 in BI by Vaibhav Ameta (17.6k points)

Browse Categories