-
Notifications
You must be signed in to change notification settings - Fork 0
/
404. Sum of Left Leaves
32 lines (29 loc) · 1.13 KB
/
404. Sum of Left Leaves
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# one code: 36ms, 95%; 39ms, 77%; 36ms, 95%
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# going through the tree: [3] --> [9], 1 (<- 9) --> [20], 0 --> [15] ,1 (<-- 15) --> [7],0 (<-- 0)--> None, 1 (<-- 0) --> None
class Solution(object):
def helper (self, root, flag):
if root == None:
return 0
if root.left == None and root.right == None and flag == 1:
return root.val
result = self.helper (root.left, 1)
result += self.helper (root.right, 0)
return result
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# how to determine it is left leaf? --> root.left == None and root.right == None and flag == 1--> this is left leaf, #return value
# self.helper (root.left, 1) , self.helper (root.right, 0)
if root == None:
return 0
result = self.helper (root.left, 1)
result += self.helper (root.right, 0)
return result