mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #534 from KelvinG-611/master
更改, 添加404.左叶子之和python部分代码
This commit is contained in:
@ -205,25 +205,51 @@ class Solution {
|
||||
|
||||
|
||||
Python:
|
||||
```Python
|
||||
|
||||
**递归**
|
||||
# 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
|
||||
```python
|
||||
class Solution:
|
||||
def sumOfLeftLeaves(self, root: TreeNode) -> int:
|
||||
self.res=0
|
||||
def areleftleaves(root):
|
||||
if not root:return
|
||||
if root.left and (not root.left.left) and (not root.left.right):self.res+=root.left.val
|
||||
areleftleaves(root.left)
|
||||
areleftleaves(root.right)
|
||||
areleftleaves(root)
|
||||
return self.res
|
||||
if not root:
|
||||
return 0
|
||||
|
||||
left_left_leaves_sum = self.sumOfLeftLeaves(root.left) # 左
|
||||
right_left_leaves_sum = self.sumOfLeftLeaves(root.right) # 右
|
||||
|
||||
cur_left_leaf_val = 0
|
||||
if root.left and not root.left.left and not root.left.right:
|
||||
cur_left_leaf_val = root.left.val # 中
|
||||
|
||||
return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum
|
||||
```
|
||||
|
||||
**迭代**
|
||||
```python
|
||||
class Solution:
|
||||
def sumOfLeftLeaves(self, root: TreeNode) -> int:
|
||||
"""
|
||||
Idea: Each time check current node's left node.
|
||||
If current node don't have one, skip it.
|
||||
"""
|
||||
stack = []
|
||||
if root:
|
||||
stack.append(root)
|
||||
res = 0
|
||||
|
||||
while stack:
|
||||
# 每次都把当前节点的左节点加进去.
|
||||
cur_node = stack.pop()
|
||||
if cur_node.left and not cur_node.left.left and not cur_node.left.right:
|
||||
res += cur_node.left.val
|
||||
|
||||
if cur_node.left:
|
||||
stack.append(cur_node.left)
|
||||
if cur_node.right:
|
||||
stack.append(cur_node.right)
|
||||
|
||||
return res
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
> 递归法
|
||||
|
Reference in New Issue
Block a user