LeetCode 404. Sum of Left Leaves

题目

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

Example:

1
2
3
4
5
6
7
8

3
/ \
9 20
/ \
15 7

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

思路

Recursion.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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:
if root is None:
return 0
res = self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
if root.left and root.left.left is None and root.left.right is None:
res += root.left.val
return res