LeetCode 题解工作台
最大层内元素和
给你一个二叉树的根节点 root 。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。 返回总和 最大 的那一层的层号 x 。如果有多层的总和一样大,返回其中 最小 的层号 x 。 示例 1: 输入: root = [1,7,0,7,-8,null,null] 输出: 2 解…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
BFS 层次遍历,求每一层的节点和,找出节点和最大的层,若有多个层的节点和最大,则返回最小的层。 具体地,我们使用一个队列 来存储当前层的节点。每次遍历时,我们记录当前层的节点和 ,然后将当前层的所有节点的子节点加入队列中,准备遍历下一层。我们使用变量 来记录当前最大的节点和,使用变量 来记录对应的层号。每次计算完一层的节点和后,如果 大于 ,则更新 和 。最后返回 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
返回总和 最大 的那一层的层号 x。如果有多层的总和一样大,返回其中 最小 的层号 x。
示例 1:

输入:root = [1,7,0,7,-8,null,null] 输出:2 解释: 第 1 层各元素之和为 1, 第 2 层各元素之和为 7 + 0 = 7, 第 3 层各元素之和为 7 + -8 = -1, 所以我们返回第 2 层的层号,它的层内元素之和最大。
示例 2:
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127] 输出:2
提示:
- 树中的节点数在
[1, 104]范围内 -105 <= Node.val <= 105
解题思路
方法一:BFS
BFS 层次遍历,求每一层的节点和,找出节点和最大的层,若有多个层的节点和最大,则返回最小的层。
具体地,我们使用一个队列 来存储当前层的节点。每次遍历时,我们记录当前层的节点和 ,然后将当前层的所有节点的子节点加入队列中,准备遍历下一层。我们使用变量 来记录当前最大的节点和,使用变量 来记录对应的层号。每次计算完一层的节点和后,如果 大于 ,则更新 和 。最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为二叉树的节点数。
# 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 maxLevelSum(self, root: Optional[TreeNode]) -> int:
q = deque([root])
mx = -inf
i = 0
while q:
i += 1
s = 0
for _ in range(len(q)):
node = q.popleft()
s += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if mx < s:
mx = s
ans = i
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate correctly identifies that BFS is the most suitable approach for level-order traversal.
- question_mark
Candidate demonstrates understanding of state tracking while performing BFS to calculate sums.
- question_mark
Candidate handles multiple levels with the same sum, returning the smallest level.
常见陷阱
外企场景- error
Failing to account for the case where multiple levels have the same sum and not returning the smallest level.
- error
Incorrectly calculating the sum for each level, leading to the wrong level being returned.
- error
Using an inefficient traversal method like DFS, which may not handle large trees as well as BFS in this case.
进阶变体
外企场景- arrow_right_alt
Modify the problem to return the level with the smallest sum rather than the largest.
- arrow_right_alt
Instead of returning the level number, return the sum at the level with the maximum sum.
- arrow_right_alt
Handle edge cases with trees that only contain one node, returning level 1.