当前位置:网站首页>leetcode-1161: Maximum in-layer element sum
leetcode-1161: Maximum in-layer element sum
2022-07-31 01:44:00 【chrysanthemum bat】
题目
给你一个二叉树的根节点 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;
}
};
边栏推荐
- 关于Redis相关内容的基础学习
- 1782. Count the number of point pairs Double pointer
- The difference between 4G communication module CAT1 and CAT4
- C language _ structure pointer array function voting system
- 简易表白小页面
- 充电效果模拟
- MySQL的安装教程(嗷嗷详细,包教包会~)
- coldfusion8后台计划任务拿shell
- MySQL installation tutorial (detailed, package teaching package~)
- Likou Daily Question - Day 46 - 704. Binary Search
猜你喜欢
prometheus 监控概述
太阳能板最大面积 od js
Word/Excel 固定表格大小,填写内容时,表格不随单元格内容变化
Analyze the capabilities and scenarios of the cloud native message flow system Apache Pulsar
"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
TiDB 在多点数字化零售场景下的应用
数字图像隐写术之JPEG 隐写分析
第一学年课程期末考试
MySql installation and configuration super detailed tutorial and simple method of building database and table
黄东旭:TiDB的优势是什么?
随机推荐
Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
黄东旭:TiDB的优势是什么?
TiDB 操作实践 -- 备份与恢复
观察者(observer)模式(一)
Know what DTU is 4GDTU equipment
Arbitrum 专访 | L2 Summer, 脱颖而出的 Arbitrum 为开发者带来了什么?
Likou Daily Question - Day 46 - 704. Binary Search
Distributed. Distributed lock
蛮力法/邻接表 广度优先 有向带权图 无向带权图
tkinter模块高级操作(二)—— 界面切换效果、立体阴影字效果及gif动图的实现
软件测试工作3年了,谈谈我是如何从刚入门进阶到自动化测试的?
TiDB之rawkv升级之路v5.0.4--&gt;v6.1.0
87. Convert String to Integer
PDF 拆分/合并
leetcode-1161:最大层内元素和
"Actual Combat" based on part-of-speech extraction in the field of e-commerce and its decision tree model modeling
【flask入门系列】Flask-SQLAlchemy的使用
Simple confession page
rpm安装postgresql12
软件测试报告有哪些内容?