File tree Expand file tree Collapse file tree 1 file changed +41
-15
lines changed
Expand file tree Collapse file tree 1 file changed +41
-15
lines changed Original file line number Diff line number Diff line change @@ -205,25 +205,51 @@ class Solution {
205205
206206
207207Python:
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
216211class 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+
227253Go:
228254
229255> 递归法
You can’t perform that action at this time.
0 commit comments