404. 左叶子之和
计算给定二叉树的所有左叶子之和。
示例:
3
/ \
9 20
/ \
15 7
在这个二叉树中,有两个左叶子,分别是 9
和 15
,所以返回 24
思路:
- 递归的方法解决
- 判断当前节点的左子节点是否是叶子节点
- 递归处理当前节点的左子树和右子树
# 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):
"""
:type root: TreeNode
:rtype: int
"""
count = 0
if not root:
return 0
if root.left:
if not root.left.left and not root.left.right:
count += root.left.val
count += self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
return count