"""
计算给定二叉树的所有左叶子之和。

示例：

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中，有两个左叶子，分别是 9 和 15，所以返回 24

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/sum-of-left-leaves
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
from typing import *


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class LeftLeafSumSolution:
    def leftLeafAdd(self, root: TreeNode, isLeft: bool) -> int:
        count = 0
        if root is None:
            return count
        if root.left is None and root.right is None and isLeft:
            return root.val
        if root.left is not None:
            count += self.leftLeafAdd(root.left, True)
        if root.right is not None:
            count += self.leftLeafAdd(root.right, False)
        return count

    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        if root is None or (root.left == root.right == None):
            return 0
        else:
            count = 0
            count += self.leftLeafAdd(root.left, True)
            count += self.leftLeafAdd(root.right, False)
        return count
