当前位置:网站首页>leetcode-1161:最大层内元素和
leetcode-1161:最大层内元素和
2022-07-31 01:33:00 【菊头蝙蝠】
题目
给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。
示例 1:
输入:root = [1,7,0,7,-8,null,null]
输出:2
解释:
第 1 层各元素之和为 1,
第 2 层各元素之和为 7 + 0 = 7,
第 3 层各元素之和为 7 + -8 = -1,
所以我们返回第 2 层的层号,它的层内元素之和最大。
示例 2:
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127]
输出:2
解题
方法一:层序遍历
class Solution {
public:
int maxLevelSum(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int maxSum=INT_MIN;
int res=1;
int depth=1;
while(!q.empty()){
int l=q.size();
int sum=0;
for(int i=0;i<l;i++){
TreeNode* cur=q.front();
q.pop();
sum+=cur->val;
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
if(sum>maxSum){
maxSum=sum;
res=depth;
}
depth++;
}
return res;
}
};
边栏推荐
- ROS Action通信
- 什么是理想的大学生活?
- tensorflow与GPU版本对应安装问题
- JPEG Steganalysis of Digital Image Steganography
- "Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
- 手把手教你配置Jenkins自动化邮件通知
- Sping.事务的传播特性
- Bert usage and word prediction based on Keras_bert model
- 数字图像隐写术之JPEG 隐写分析
- MySql的安装配置超详细教程与简单的建库建表方法
猜你喜欢

ShardingSphere read-write separation (8)

软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?

The Meta Metaverse Division lost 2.8 billion in the second quarter, still want to continue to bet?Metaverse development has yet to see a way out

In Google Cloud API gateway APISIX T2A and T2D performance test

Installation problem corresponding to tensorflow and GPU version

Bert usage and word prediction based on Keras_bert model

I have been working in software testing for 3 years, how did I go from just getting started to automated testing?

GCC Rust获批将被纳入主线代码库,或将于GCC 13中与大家见面

35. Reverse linked list

九州云入选“可信云最新评估体系及2022年通过评估企业名单”
随机推荐
pycharm重命名后无法运行(报错: can‘t open file......No such file or directory)
Mysql: Invalid default value for TIMESTAMP
Rocky/GNU之Zabbix部署(3)
计算S=a+aa+…+aa…a
蛮力法/邻接表 广度优先 有向带权图 无向带权图
case语句的综合结果,你究竟会了吗?【Verilog高级教程】
观察者(observer)模式(一)
Yolov7实战,实现网页端的实时目标检测
打印任务排序 js od华为
ROS Action communication
297. 二叉树的序列化与反序列化
蛮力法/邻接矩阵 广度优先 有向带权图 无向带权图
程序员转正述职报告/总结
MySQL的存储过程
【微信小程序】一文带你了解数据绑定、事件绑定以及事件传参、数据同步
rpm安装postgresql12
"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
24. Please talk about the advantages and disadvantages of the singleton pattern, precautions, usage scenarios
Rocky/GNU之Zabbix部署(2)
《MySQL数据库进阶实战》读后感(SQL 小虚竹)