-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path404.SumofLeftLeaves.py
41 lines (35 loc) · 1.11 KB
/
404.SumofLeftLeaves.py
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
33
34
35
36
37
38
39
40
41
"""
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15
respectively. Return 24.
"""
#Difficulty: Easy
#102 / 102 test cases passed.
#Runtime: 28 ms
#Memory Usage: 14.2 MB
#Runtime: 28 ms, faster than 91.15% of Python3 online submissions for Sum of Left Leaves.
#Memory Usage: 14.2 MB, less than 78.35% of Python3 online submissions for Sum of Left Leaves.
# 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:
result = []
self.preorder(root, result)
return sum(result)
def preorder(self, root, result):
if not root:
return 0
if root.left and not root.left.left and not root.left.right:
result.append(root.left.val)
self.preorder(root.left, result)
self.preorder(root.right, result)