当前位置:网站首页>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;
}
}
边栏推荐
- Chengdu openGauss user group recruit!
- Project Background Technology Express
- Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
- 密码学的基础:X.690和对应的BER CER DER编码
- Redis for distributed applications in Golang
- The characteristics and principle of typescript29 - enumeration type
- Hash collisions and consistent hashing
- bool Frame::PosInGrid(const cv::KeyPoint &kp, int &posX, int &posY)
- Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
- 垃圾回收器CMS和G1
猜你喜欢
2022-07-30 mysql8执行慢SQL-Q17分析
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
Chengdu openGauss user group recruit!
【轮式里程计】
秒懂大模型 | 3步搞定AI写摘要
AWR分析报告问题求助:SQL如何可以从哪几个方面优化?
Hash collisions and consistent hashing
Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval
typescript36-class的构造函数实例方法
个人博客系统项目测试
随机推荐
MySQL8 下载、启动、配置、验证
检查IP或端口是否被封
6-25 Vulnerability Exploitation - irc Backdoor Exploitation
Garbage Collector CMS and G1
密码学的基础:X.690和对应的BER CER DER编码
Basic use of typescript34-class
From 2023 onwards, these regions will be able to obtain a certificate with a score lower than 45 in the soft examination.
Coding Experience Talk
Named parameter implementation of JDBC PreparedStatement
求大神解答,这种 sql 应该怎么写?
"NetEase Internship" Weekly Diary (2)
Personal blog system project test
垃圾回收器CMS和G1
数据链路层的数据传输
超大规模的产业实用语义分割数据集PSSL与预训练模型开源啦!
Constructor of typescript35-class
The Paddle Open Source Community Quarterly Report is here, everything you want to know is here
优炫数据库导库导错了能恢复吗?
编码经验之谈
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021: Interpretation