当前位置:网站首页>LeetCode 1161 The largest element in the layer and the LeetCode road of [BFS binary tree] HERODING
LeetCode 1161 The largest element in the layer and the LeetCode road of [BFS binary tree] HERODING
2022-07-31 02:10:00 【HERODING23】

解题思路
套用BFSThe template can easily solve this problem,首先定义队列,Used to store nodes in layer order,Then iterate through each layer in the queue,统计总和,And update the number of layers where the maximum sum is located,so on until the queue is empty,It also means that the binary tree has been traversed,代码如下:
代码
/** * 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;
}
};
边栏推荐
猜你喜欢

STM32CUBEMX开发GD32F303(11)----ADC在DMA模式下扫描多个通道

leetcode-952: Calculate max component size by common factor

直播预告 | KDD2022博士论文奖冠亚军对话

静态路由解析(最长掩码匹配原则+主备路由)

How to design the changing system requirements

To write good test cases, you must first learn test design

vlan间路由+静态路由+NAT(PAT+静态NAT)综合实验

类似 MS Project 的项目管理工具有哪些

leetcode-1161: Maximum in-layer element sum

图像处理技术的心酸史
随机推荐
软件测试基础接口测试-入门Jmeter,你要注意这些事
GCC Rust is approved to be included in the mainline code base, or will meet you in GCC 13
曼城推出可检测情绪的智能围巾,把球迷给整迷惑了
CV-Model [3]: MobileNet v2
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文
12 pictures take you to fully understand service current limit, circuit breaker, downgrade, and avalanche
"Cloud native's master, master and vulgar skills" - 2022 National New College Entrance Examination Volume I Composition
keep-alive缓存组件
STP选举(步骤+案列)详解
Shell 脚本循环遍历日志文件中的值进行求和并计算平均值,最大值和最小值
最大路径和
充电效果模拟
uniapp uses 3rd party fonts
MPPT太阳能充放电控制器数据采集-通过网关采集电池电压容量电量SOC,wifi传输
Unity界面总体介绍
修改未正确放入沙盒造成苹果兼容性问题
Tower of Hanoi problem
MySQL的分页你还在使劲的limit?
The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]
类似 MS Project 的项目管理工具有哪些