当前位置:网站首页>LeetCode-1161. 最大层内元素和
LeetCode-1161. 最大层内元素和
2022-08-03 11:29: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
提示:
树中的节点数在 [1, 104]范围内
-105 <= Node.val <= 105
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include<queue>
class Solution {
public:
int maxLevelSum(TreeNode* root) {
int level = 1; //层级
int maxVal = INT_MIN;
int maxLevel = level;
mq.push(root);
while(!mq.empty()){
int sum = 0; //层级和
int len = mq.size();
while(len--){
TreeNode *t = mq.front();
if(t->left){
mq.push(t->left);
}
if(t->right){
mq.push(t->right);
}
sum+=t->val;
mq.pop();
}
//计算最大
if(maxVal < sum){
maxVal = sum;
maxLevel = level;
}
level++; //层级递增
}
return maxLevel;
}
private:
queue<TreeNode *> mq;
};边栏推荐
- 【JS 逆向百例】某网站加速乐 Cookie 混淆逆向详解
- Machines need tokens more than people
- RTP协议分析
- Lease recovery system based on PHP7.2+MySQL5.7
- 数据库一席谈:打造开源的数据生态,支撑产业数字化浪潮
- [LeetCode—Question 2 Sum of Two Numbers Detailed Code Explanation ] The source code is attached, which can be copied directly
- [Explanation of JDBC and inner classes]
- Activiti产生的背景和作用
- Why is the new earth blurred, in-depth analysis of white balls, viewing pictures, and downloading problems
- 【一起学Rust】Rust包管理工具Cargo初步了解
猜你喜欢
【一起学Rust 基础篇】Rust基础——变量和数据类型

GET 和 POST 有什么区别?
![[LeetCode—Question 2 Sum of Two Numbers Detailed Code Explanation ] The source code is attached, which can be copied directly](/img/19/a3f58d5a1150d99571205a7e2f7345.png)
[LeetCode—Question 2 Sum of Two Numbers Detailed Code Explanation ] The source code is attached, which can be copied directly

程序员架构修炼之道:软件架构基本概念和思维

通过组策略安装软件和删除用户配置文件

html+css+php+mysql实现注册+登录+修改密码(附完整代码)

ABAB-740新语法

机器学习(第一章)—— 特征工程

性能优化|从ping延时看CPU电源管理

asdn涨薪技术之apifox+Jenkins如何玩转接口自动化测试
随机推荐
记住用户名案例(js)
【MySQL功法】第2话 · 数据库与数据表的基本操作
ETL data cleaning case in MapReduce
增加WebView对localStorage的支持
FR9811S6 SOT-23-6 23V, 2A Synchronous Step-Down DC/DC Converter
ABAB-740新语法
微信小程序获取用户手机号码
永寿 永寿农特产品-苹果
CADEditorX ActiveX 14.1.X
【无标题】函数,对象,方法的区别
当前页面的脚本发生错误如何解决_电脑出现当前页面脚本错误怎么办
MySQL database combat (1)
如何检索IDC研究报告?
技术总监需要会些什么?也太难了!
C#/VB.NET 从PDF中提取表格
直播弱网优化
【Star项目】小帽飞机大战(九)
build --repot
complete knapsack problem
本周四晚19:00知识赋能第4期直播丨OpenHarmony智能家居项目之设备控制实现