当前位置:网站首页>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;
}
}

边栏推荐
- Redis 订阅与 Redis Stream
- LeetCode刷题日记:53、最大子数组和
- Personal blog system project test
- From 2023 onwards, these regions will be able to obtain a certificate with a score lower than 45 in the soft examination.
- AntPathMatcher uses
- 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
- 软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3
- 『网易实习』周记(一)
- 【LeetCode每日一题】——654.最大二叉树
- 【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
猜你喜欢
随机推荐
typescript31-any类型
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3
typescript29-枚举类型的特点和原理
【ORB_SLAM2】SetPose、UpdatePoseMatrices
Centos7 安装postgresql并开启远程访问
openGauss切换后state状态显示不对
"NetEase Internship" Weekly Diary (1)
Typescript31 - any type
Simple example of libcurl accessing url saved as file
【LeetCode每日一题】——654.最大二叉树
Huawei's 5-year female test engineer resigns: what a painful realization...
6-25 Vulnerability Exploitation - irc Backdoor Exploitation
The ultra-large-scale industrial practical semantic segmentation dataset PSSL and pre-training model are open source!
typescript30 - any type
Redis Persistence - RDB and AOF
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
编码经验之谈
Handwritten Blog Platform ~ Day Two
typescript38-class的构造函数实例方法继承(implement)
to-be-read list

![[LeetCode Daily Question] - 103. Zigzag Level Order Traversal of Binary Tree](/img/b9/35813ae2972375fa728e3c11fab5d3.png)







