Python Recursion Didn't Give Correct Result for "Sum of Left Leaves"

I wrote a code for the leetcode problem "108. Sum of Left Leaves" using recursion. It didn't give me the expected result.


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:

            return 0

        ans = 0

        if root.left and not root.left.left and not root.left.right:

            ans += root.left.val


        self.sumOfLeftLeaves(root.left)
        self.sumOfLeftLeaves(root.right)

        return ans

When the input is [3,9,20,null,null,15,7]

I expected a 24 to be returned, but the code only gave me 9

1 Answer

You aren't adding the results of the leaves below the root. You need this:

class Solution(object):
    def sumOfLeftLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:

            return 0

        ans = 0

        if root.left and not root.left.left and not root.left.right:
            ans += root.left.val

        ans += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

        return ans
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest