Skip to content

Commit 62be9cf

Browse files
committed
Merge branch 'master' into 513.找树左下角的值
2 parents 1dd4a52 + 8c53c48 commit 62be9cf

File tree

1 file changed

+41
-15
lines changed

1 file changed

+41
-15
lines changed

problems/0404.左叶子之和.md

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -205,25 +205,51 @@ class Solution {
205205

206206

207207
Python:
208-
```Python
208+
209209
**递归**
210-
# Definition for a binary tree node.
211-
# class TreeNode:
212-
# def __init__(self, val=0, left=None, right=None):
213-
# self.val = val
214-
# self.left = left
215-
# self.right = right
210+
```python
216211
class Solution:
217212
def sumOfLeftLeaves(self, root: TreeNode) -> int:
218-
self.res=0
219-
def areleftleaves(root):
220-
if not root:return
221-
if root.left and (not root.left.left) and (not root.left.right):self.res+=root.left.val
222-
areleftleaves(root.left)
223-
areleftleaves(root.right)
224-
areleftleaves(root)
225-
return self.res
213+
if not root:
214+
return 0
215+
216+
left_left_leaves_sum = self.sumOfLeftLeaves(root.left) #
217+
right_left_leaves_sum = self.sumOfLeftLeaves(root.right) #
218+
219+
cur_left_leaf_val = 0
220+
if root.left and not root.left.left and not root.left.right:
221+
cur_left_leaf_val = root.left.val #
222+
223+
return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum
226224
```
225+
226+
**迭代**
227+
```python
228+
class Solution:
229+
def sumOfLeftLeaves(self, root: TreeNode) -> int:
230+
"""
231+
Idea: Each time check current node's left node.
232+
If current node don't have one, skip it.
233+
"""
234+
stack = []
235+
if root:
236+
stack.append(root)
237+
res = 0
238+
239+
while stack:
240+
# 每次都把当前节点的左节点加进去.
241+
cur_node = stack.pop()
242+
if cur_node.left and not cur_node.left.left and not cur_node.left.right:
243+
res += cur_node.left.val
244+
245+
if cur_node.left:
246+
stack.append(cur_node.left)
247+
if cur_node.right:
248+
stack.append(cur_node.right)
249+
250+
return res
251+
```
252+
227253
Go:
228254

229255
> 递归法

0 commit comments

Comments
 (0)