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

边栏推荐
- Understand the big model in seconds | 3 steps to get AI to write a summary
- messy website
- Project Background Technology Express
- Huawei's 5-year female test engineer resigns: what a painful realization...
- 电子制造仓储条码管理系统解决方案
- 求大神解答,这种 sql 应该怎么写?
- Hiring a WordPress Developer: 4 Practical Ways
- Handwriting a blogging platform ~ Day 3
- 手写一个博客平台~第三天
- 【LeetCode每日一题】——654.最大二叉树
猜你喜欢

Check if IP or port is blocked

项目后台技术Express

力扣 1161. 最大层内元素和

typescript34-class的基本使用

『网易实习』周记(一)

飞桨助力航天宏图PIE-Engine地球科学引擎构建

Understand the big model in seconds | 3 steps to get AI to write a summary
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3

3. Bean scope and life cycle

From 2023 onwards, these regions will be able to obtain a certificate with a score lower than 45 in the soft examination.
随机推荐
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
Redis for distributed applications in Golang
Day116.尚医通:预约挂号详情 ※
手写一个博客平台~第一天
Handwriting a blogging platform ~ the first day
Force buckle, 752-open turntable lock
Rasa 3.x 学习系列- Rasa - Issues 4873 dispatcher.utter_message 学习笔记
编码经验之谈
typescript32-ts中的typeof
LeetCode 213. Robbery II (2022.08.01)
The characteristics and principle of typescript29 - enumeration type
Data transfer at the data link layer
typeof in typescript32-ts
MySQL optimization strategy
垃圾回收器CMS和G1
【ORB_SLAM2】void Frame::AssignFeaturesToGrid()
Constructor instance method inheritance of typescript37-class (extends)
Use baidu EasyDL implement factory workers smoking behavior recognition
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
Named parameter implementation of JDBC PreparedStatement