404_Sum of Left Leaves

404. Sum of Left Leaves

Level: easy

Tag: tree

Question

Find the sum of all left leaves in a given binary tree.

Example 1

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

Solution 1: recursive (w/o defining a helper function)

# 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
        """
        res = 0

        if not root:
            return res

        if root.left and not root.left.left and not root.left.right:
            res += root.left.val
        else:
            res += self.sumOfLeftLeaves(root.left)

        if root.right:
            res += self.sumOfLeftLeaves(root.right)
        return res

Solution 2: iterative (Depth first search, using stack)

Last updated