-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy path404_Sum_of_Left_Leaves.py
32 lines (30 loc) · 1.04 KB
/
404_Sum_of_Left_Leaves.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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
# def sumOfLeftLeaves(self, root):
# """
# :type root: TreeNode
# :rtype: int
# """
# if root is None:
# return 0
# if root.left is not None:
# if root.left.left is None and root.left.right is None:
# return root.left.val + self.sumOfLeftLeaves(root.right)
# return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
def sumOfLeftLeaves(self, root):
stack = [root]
res = 0
while len(stack) > 0:
curr = stack.pop(0)
if curr is not None:
if curr.left is not None:
if curr.left.left is None and curr.left.right is None:
res += curr.left.val
stack.insert(0, curr.right)
stack.insert(0, curr.left)
return res