当前位置:网站首页>力扣 1161. 最大层内元素和
力扣 1161. 最大层内元素和
2022-08-02 01:02:00 【冷酷的摸鱼小将】
题目
给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。
示例

输入:root = [1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大。
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:BFS
Java实现
class Solution {
public int maxLevelSum(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int res = -1, step = 1;
int sum, max = Integer.MIN_VALUE;
while (!q.isEmpty()) {
sum = 0;
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode cur = q.poll();
sum += cur.val;
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
if (sum > max) {
max = sum;
res = step;
}
step++;
}
return res;
}
}

边栏推荐
猜你喜欢
随机推荐
管理基础知识9
dayjs时间处理库的基本使用
Kubernetes — 核心资源对象 — 存储
IDEA如何运行web程序
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
22.卷积神经网络实战-Lenet5
flex布局中使用flex-wrap实现换行
ELK日志分析系统
【刷题篇】打家劫舍
Mapped Statements collection does not contain value for的解决方法
Debian侵犯Rust商标,妥协改名还是会得到豁免?
PowerBI商学院佐罗BI真经连续剧
Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits
传统企业数字化转型需要经过几个阶段?
Reflex WMS中阶系列7:已经完成拣货尚未Load的HD如果要取消拣货,该如何处理?
60种特征工程操作:使用自定义聚合函数【收藏】
About MySQL data insertion (advanced usage)
JS中localStorage和sessionStorage
Kubernetes — 核心资源对象 — Controller
第一次写对牛客的编程面试题:输入一个字符串,返回该字符串出现最多的字母









