当前位置:网站首页>Ringtone 1161. Maximum In-Layer Elements and
Ringtone 1161. Maximum In-Layer Elements and
2022-08-02 02:08:00 【cold-blooded fisherman】
题目
给你一个二叉树的根节点 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;
}
}

边栏推荐
- typescript33-typescript高级概述
- typescript36-class的构造函数实例方法
- Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
- 垃圾回收器CMS和G1
- "NetEase Internship" Weekly Diary (1)
- Win Go development kit installation configuration, GoLand configuration
- 3. Bean scope and life cycle
- Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation
- Rust P2P Network Application Combat-1 P2P Network Core Concepts and Ping Program
- 优炫数据库导库导错了能恢复吗?
猜你喜欢

Day116.尚医通:预约挂号详情 ※

AOF重写

使用百度EasyDL实现厂区工人抽烟行为识别

Constructor instance method inheritance of typescript38-class (implement)

超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!

用位运算为你的程序加速

Win Go development kit installation configuration, GoLand configuration

MySQL优化策略

3. Bean scope and life cycle

Record the pits where an error occurs when an array is converted to a collection, and try to use an array of packaging types for conversion
随机推荐
[ORB_SLAM2] void Frame::ComputeImageBounds(const cv::Mat & imLeft)
Redis Persistence - RDB and AOF
LeetCode brush diary: LCP 03. Machine's adventure
Force buckle, 752-open turntable lock
[LeetCode Daily Question] - 103. Zigzag Level Order Traversal of Binary Tree
Effects of Scraping and Aggregation
LeetCode刷题日记:53、最大子数组和
C language inserted into the characters of simple exercises
AOF rewrite
Constructor instance method of typescript36-class
LeetCode brushing diary: 33. Search and rotate sorted array
2022-08-01 安装mysql监控工具phhMyAdmin
乱七八糟的网站
Golang分布式应用之Redis
力扣 1374. 生成每种字符都是奇数个的字符串
swift project, sqlcipher3 -> 4, cannot open legacy database is there a way to fix it
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
Win Go development kit installation configuration, GoLand configuration
Huawei's 5-year female test engineer resigns: what a painful realization...
YGG Guild Development Plan Season 1 Summary