当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
934. The Shortest Bridge
Static route analysis (the longest mask matching principle + active and standby routes)
Static routing + PAT + static NAT (explanation + experiment)
最大路径和
vlan间路由+静态路由+NAT(PAT+静态NAT)综合实验
coldfusion8后台计划任务拿shell
第一学年课程期末考试
Drools Rule Properties, Advanced Syntax
Crypto Life, a day in the life of a Web3 project partner
multiplayer-hlap 包有问题,无法升级的解决方案
随机推荐
What level of software testing does it take to get a 9K job?
Drools规则属性,高级语法
User interaction + formatted output
MySQL stored procedure
Programmer's debriefing report/summary
pc端判断当前使用浏览器类型
mysql 索引
Drools basic introduction, introductory case, basic syntax
蛮力法/邻接表 广度优先 有向带权图 无向带权图
Drools WorkBench的简介与使用
tcp框架需要解决的问题
STP选举(步骤+案列)详解
软件测试基础接口测试-入门Jmeter,你要注意这些事
What is the ideal college life?
Problems that need to be solved by the tcp framework
Crawler text data cleaning
[1153] The boundary range of between in mysql
MySQL的分页你还在使劲的limit?
Basic introduction to ShardingJDBC
pycharm cannot run after renaming (error: can't open file...No such file or directory)