当前位置:网站首页>力扣 1161. 最大层内元素和
力扣 1161. 最大层内元素和
2022-08-02 01:02:00 【冷酷的摸鱼小将】
题目
给你一个二叉树的根节点 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;
}
}

边栏推荐
- 如何期货开户和选择期货公司?
- 信息收集之目录扫描-dirbuster
- Mapped Statements collection does not contain value for的解决方法
- Maxwell 一款简单易上手的实时抓取Mysql数据的软件
- ERROR 1064 (42000) You have an error in your SQL syntax; check the manual that corresponds to your
- 安全(1)
- 期货开户手续费加一分是主流
- Kubernetes之本地存储
- 接口(第九天)
- Can't connect to MySQL server on 'localhost3306' (10061) Simple and clear solution
猜你喜欢

Some insights from 5 years of automated testing experience: UI automation must overcome these 10 pits

期货开户手续费的秘密成了透明

go泛型使用方法

Pytorch seq2seq model architecture to achieve English translation tasks

canal realizes mysql data synchronization

外包干了三年,废了...

IDEA找不到Database解决方法

22.卷积神经网络实战-Lenet5

大话西游创建角色失败解决

go mode tidy出现报错go warning “all“ matched no packages
随机推荐
6-25漏洞利用-irc后门利用
About MySQL data insertion (advanced usage)
如何期货开户和选择期货公司?
Why is on-chain governance so important, and how will Polkadot Gov 2.0 lead the development of on-chain governance?
管理基础知识13
C语言实验九 函数(一)
PowerBI商学院佐罗BI真经连续剧
期货公司开户实力经纪业务的规模
期货开户调整交易所保证金标准
Day11 Shell scripting basics
pcie inbound和outbound关系
GO GOPROXY代理设置
Kubernetes — 核心资源对象 — 网络
kubernetes之服务发现
Navicat数据显示不完全的解决方法
Pytorch seq2seq model architecture to achieve English translation tasks
go泛型使用方法
FlinkSQL CDC实现同步oracle数据到mysql
22.卷积神经网络实战-Lenet5
喜报 | AR 开启纺织产业新模式,ALVA Systems 再获殊荣!