当前位置:网站首页>LeetCode 1161 最大层内元素和[BFS 二叉树] HERODING的LeetCode之路
LeetCode 1161 最大层内元素和[BFS 二叉树] HERODING的LeetCode之路
2022-07-31 01:54:00 【HERODING23】

解题思路
套用BFS的模板可以轻松解决该题,首先定义队列,用于按层顺序存储节点,然后遍历在队列中的每一层,统计总和,并更新最大总和所在层数,如此直到队列为空,也说明二叉树已经遍历完毕,代码如下:
代码
/** * 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) {} * }; */
class Solution {
public:
int maxLevelSum(TreeNode* root) {
queue<TreeNode*> q;
int maxNum = INT_MIN;
int layer = 1;
int cur = 0;
q.emplace(root);
while(!q.empty()) {
cur ++;
int n = q.size();
int total = 0;
for(int i = 0; i < n; i ++) {
TreeNode* temp = q.front();
total += temp->val;
if(temp->left != nullptr) {
q.emplace(temp->left);
}
if(temp->right != nullptr) {
q.emplace(temp->right);
}
q.pop();
}
if(total > maxNum) {
maxNum = total;
layer = cur;
}
}
return layer;
}
};
边栏推荐
- leetcode-128: longest continuous sequence
- Calculate S=a+aa+…+aa…a
- 《MySQL数据库进阶实战》读后感(SQL 小虚竹)
- Between two orderly array of additive and Topk problem
- Crypto Life, a day in the life of a Web3 project partner
- 初识C语言 -- 数组
- User interaction + formatted output
- Software Testing Defect Reporting - Definition, Composition, Defect Lifecycle, Defect Tracking Post-Production Process, Defect Tracking Process, Purpose of Defect Tracking, Defect Management Tools
- 静态路由解析(最长掩码匹配原则+主备路由)
- 最大路径和
猜你喜欢

Interprocess communication study notes

最大路径和

The real CTO is a technical person who understands products
![The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]](/img/8a/28427aa773e46740eda9e95f6669f2.png)
The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]

汉诺塔问题

rpm install postgresql12

16、注册中心-consul

Static route analysis (the longest mask matching principle + active and standby routes)

力扣刷题之有效的正方形(每日一题7/29)

221. Largest Square
随机推荐
Introduction and use of Drools WorkBench
什么是理想的大学生活?
tcp框架需要解决的问题
Validate XML documents
leetcode-399:除法求值
软件测试缺陷报告---定义,组成,缺陷的生命周期,缺陷跟踪产后处理流程,缺陷跟踪处理流程,缺陷跟踪的目的,缺陷管理工具
Can an inexperienced college graduate switch to software testing?my real case
Software testing basic interface testing - getting started with Jmeter, you should pay attention to these things
如何在 go 程序中暴露 Prometheus 指标
MySQL的分页你还在使劲的limit?
vlan间路由+静态路由+NAT(PAT+静态NAT)综合实验
Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值
rpm安装postgresql12
软件测试基础接口测试-入门Jmeter,你要注意这些事
The effective square of the test (one question of the day 7/29)
成为比开发硬气的测试人,我都经历了什么?
pc端判断当前使用浏览器类型
mmdetection训练一个模型相关命令
CV-Model【3】:MobileNet v2
934. The Shortest Bridge