Sum of Left Leaves

Problem Id: 404 Difficulty: Easy Tag: Tree


This problem could be solved by using one additional variable to mark the current node is a left node or right node of its parent. And in the DFS function, we could use the sum of left leaves as the return value.


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

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        return self._helper(root, left=False)

    def _helper(self, node, left):
        if node is None:
            return 0
        s = self._helper(node.left, True) + self._helper(node.right, False)
        if node.left is None and node.right is None and left:
            s += node.val
        return s