当前位置:网站首页>力扣 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;
}
}
边栏推荐
猜你喜欢
管理基础知识20
ELK日志分析系统
去经营企业吧
期货开户手续费的秘密成了透明
安全(2)
datax与datax-web安装部署
ERROR 1045 (28000) Access denied for user ‘root‘@‘localhost‘解决方法
Why is on-chain governance so important, and how will Polkadot Gov 2.0 lead the development of on-chain governance?
3个月测试员自述:4个影响我职业生涯的重要技能
from origin ‘null‘ has been blocked by CORS policy Cross origin requests are only supported for
随机推荐
GateWay实现负载均衡
关于MySQL的数据插入(高级用法)
Flex布局详解
Can‘t connect to MySQL server on ‘localhost3306‘ (10061) 简洁明了的解决方法
哪里有期货开户的正规途径?
管理基础知识11
feign异常传递的两种方式 fallbackfactory和全局处理 获取服务端自定义异常
Kubernetes — 网络流量模型
简单工厂模式
5年自动化测试经验的一些感悟:做UI自动化一定要跨过这10个坑
ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
【目标检测】FCOS: Fully Convolutional One-Stage Object Detection
About MySQL data insertion (advanced usage)
创新项目实战之智能跟随机器人原理与代码实现
JS中对作用域链的理解(查找变量)
一本适合职场新人的好书
设备树学习
JS中localStorage和sessionStorage
Entry name ‘org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt’ collided
信息收集之cms指纹识别