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
3
/
9 20
/
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

思路

简单的递归求解即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class (object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
count = 0
if (root == None):
return 0
if ((root.left) and (root.left.left == None) and (root.left.right == None)):
count += root.left.val
if ( (root.left) and ( (root.left.left) or (root.left.right) ) ):
count += self.sumOfLeftLeaves(root.left)
if ( (root.right) ):
count += self.sumOfLeftLeaves(root.right)
return count