mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0404.左叶子之和.md
This commit is contained in:
@ -250,19 +250,27 @@ 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
|
||||||
class Solution:
|
class Solution:
|
||||||
def sumOfLeftLeaves(self, root: TreeNode) -> int:
|
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
|
||||||
if not root:
|
if not root:
|
||||||
return 0
|
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:
|
if root.left and not root.left.left and not root.left.right:
|
||||||
cur_left_leaf_val = root.left.val
|
left_val = root.left.val
|
||||||
|
else:
|
||||||
|
left_val = self.sumOfLeftLeaves(root.left)
|
||||||
|
|
||||||
return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum # 中
|
# 递归地计算右子树左叶节点的和
|
||||||
|
right_val = self.sumOfLeftLeaves(root.right)
|
||||||
|
|
||||||
|
return left_val + right_val
|
||||||
```
|
```
|
||||||
|
|
||||||
**迭代**
|
**迭代**
|
||||||
|
Reference in New Issue
Block a user