1302. 层数最深叶子节点的和
为保证权益,题目请参考 1302. 层数最深叶子节点的和(From LeetCode).
解决方案1
Python
python
# 1302. 层数最深叶子节点的和
# https://leetcode.cn/problems/deepest-leaves-sum/
from typing import Optional
# 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:
def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
self.deep_depth = 0
self.deep_val = 0
def dfs(root: Optional[TreeNode], depth: int):
if root is None:
return
if depth == self.deep_depth:
self.deep_val += root.val
elif depth > self.deep_depth:
self.deep_depth = depth
self.deep_val = root.val
dfs(root.left, depth + 1)
dfs(root.right, depth + 1)
dfs(root, 0)
return self.deep_val
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
33
34
35
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
33
34
35