当前位置:网站首页>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;
}
};
边栏推荐
- 基于FPGA的售货机
- Fiddler抓包模拟弱网络环境测试
- f.grid_sample
- 图像处理技术的心酸史
- The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]
- Manchester City confuses fans with smart scarf that detects emotions
- 验证整数输入
- FPGA-based vending machine
- [WeChat applet] This article takes you to understand data binding, event binding, event parameter transfer, and data synchronization
- 充电效果模拟
猜你喜欢

leetcode-1161:最大层内元素和

Detailed explanation of STP election (step + case)

英特尔软硬优化,赋能东软加速智慧医疗时代到来

"Cloud native's master, master and vulgar skills" - 2022 National New College Entrance Examination Volume I Composition

Crypto Life, a day in the life of a Web3 project partner

Drools Rule Properties, Advanced Syntax

基于FPGA的图像实时采集

Nacos

STP选举(步骤+案列)详解

最大路径和
随机推荐
Introduction and use of Drools WorkBench
mmdetection trains a model related command
Manchester City confuses fans with smart scarf that detects emotions
There is a problem with the multiplayer-hlap package and the solution cannot be upgraded
How to do a startup CTO?
BAT卖不动「医疗云」:医院逃离、山头林立、行有行规
软件测试报告有哪些内容?
Fiddler抓包模拟弱网络环境测试
Overview of prometheus monitoring
Nacos
Brute Force/Adjacency Matrix Breadth First Directed Weighted Graph Undirected Weighted Graph
ShardingJDBC使用总结
User interaction + formatted output
验证整数输入
"Cloud native's master, master and vulgar skills" - 2022 National New College Entrance Examination Volume I Composition
mysql 索引
汉诺塔问题
multiplayer-hlap 包有问题,无法升级的解决方案
Validate XML documents
934. 最短的桥