当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢

【网络安全】文件上传靶场通关(1-11关)

Overview of prometheus monitoring

Nacos

934. 最短的桥

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

leetcode-399:除法求值

leetcode-952: Calculate max component size by common factor

uniapp使用第三方字体

MySQL installation tutorial (detailed, package teaching package~)

Parameter introduction and selection points of wireless module
随机推荐
软件测试要达到一个什么水平才能找到一份9K的工作?
进程间通信学习笔记
uniapp使用第三方字体
Jiuzhou Cloud was selected into the "Trusted Cloud's Latest Evaluation System and the List of Enterprises Passing the Evaluation in 2022"
MySQL (6)
Xiaohei's leetcode journey: 117. Fill the next right node pointer of each node II
MySQL (6)
MySql installation and configuration super detailed tutorial and simple method of building database and table
coldfusion8后台计划任务拿shell
Word/Excel 固定表格大小,填写内容时,表格不随单元格内容变化
Teach you how to configure Jenkins automated email notifications
934. 最短的桥
勾股数元组 od js
聚簇索引和非聚簇索引到底有什么区别
VS warning LNK4099: No solution found for PDB
Are you still working hard on the limit of MySQL paging?
初识C语言 -- 数组
软件测试基础接口测试-入门Jmeter,你要注意这些事
rpm install postgresql12
数字图像隐写术之JPEG 隐写分析