404. Sum Of Left Leaves | LeetCode | Python | Solution

This problem description is pretty simple. The description is: find the sum of all left leaves in a given binary tree.

Here is the link of the problem.

Let’s see the tree from the example.

   / \
  9  20
    /  \
   15   7

We see a binary tree in the above example. In a binary tree, each node has at most two child nodes. On the other hand, a leaf node is a node that does not have any child nodes.

So the question tells us, we have to return the sum of left leaves. In this tree, there are three leaf nodes, which are 9, 15, 7. But 7 is not the left node. It’s the right node of 20. So, we can come up with the result 9 + 15 = 24. This is the problem we have to solve.

We will solve this problem by using recursion.

It’s mandatory to have a base case when we use recursion. First, we set a variable to store the sum of leaves nodes. Then we check the base case.

After that, we will check each node recursively. If the node doesn’t have the left and right child, we will add the value with our variable leaves_sum.

If you know recursion, it will very easy for you to understand. Let’s see the solution.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        leaves_sum = 0

        # base case
        if root is None:
            return 0

        if root.left is not None and root.left.left is None and root.left.right is None:
            leaves_sum += root.left.val
            leaves_sum += self.sumOfLeftLeaves(root.left)
        if root.right is not None:
            if root.right.left is not None or root.right.right is not None:
                leaves_sum += self.sumOfLeftLeaves(root.right)
        return leaves_sum

It’s an easy problem. If you submit the code in LeetCode, it will be accepted.