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

边栏推荐
猜你喜欢

成都openGauss用户组招募啦!

typescript37-class的构造函数实例方法继承(extends)

雇用WordPress开发人员:4个实用的方法

『网易实习』周记(三)

Win Go开发包安装配置、GoLand配置

【LeetCode每日一题】——704.二分查找

2022-08-01 mysql/stoonedb慢SQL-Q18分析

哈希冲突和一致性哈希

Day115. Shangyitong: Background user management: user lock and unlock, details, authentication list approval

typeof in typescript32-ts
随机推荐
【LeetCode每日一题】——704.二分查找
力扣(LeetCode)213. 打家劫舍 II(2022.08.01)
【LeetCode每日一题】——103.二叉树的锯齿形层序遍历
AOF rewrite
A full set of common interview questions for software testing functional testing [open thinking questions] interview summary 4-3
Win Go development kit installation configuration, GoLand configuration
使用百度EasyDL实现厂区工人抽烟行为识别
【服务器数据恢复】服务器Raid5阵列mdisk磁盘离线的数据恢复案例
typescript32-ts中的typeof
力扣、752-打开转盘锁
Software testing Interface automation testing Pytest framework encapsulates requests library Encapsulates unified request and multiple base path processing Interface association encapsulation Test cas
Handwriting a blogging platform ~ Day 3
[LeetCode Daily Question]——654. The largest binary tree
LeetCode刷题日记:153、寻找旋转排序数组中的最小值
搜罗汇总的效应
2022河南青训联赛第(三)场
软件测试功能测试全套常见面试题【开放性思维题】面试总结4-3
to-be-read list
Day115.尚医通:后台用户管理:用户锁定解锁、详情、认证列表审批
Shell Beginners Final Chapter