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

Real-time image acquisition based on FPGA

mmdetection训练一个模型相关命令

GCC Rust is approved to be included in the mainline code base, or will meet you in GCC 13

Detailed explanation of STP election (step + case)

What have I experienced to become a tester who is harder than development?

Drools WorkBench的简介与使用

英特尔软硬优化,赋能东软加速智慧医疗时代到来
![CV-Model [3]: MobileNet v2](/img/c7/1155a1f610110724c67a3b7557ef28.jpg)
CV-Model [3]: MobileNet v2

Arbitrum Interview | L2 Summer, what does the standout Arbitrum bring to developers?

加密生活,Web3 项目合伙人的一天
随机推荐
Fiddler captures packets to simulate weak network environment testing
AI中的数学思想
Unity界面总体介绍
直播预告 | KDD2022博士论文奖冠亚军对话
uniapp uses 3rd party fonts
Inner monologue from a female test engineer...
【AcWing 62nd Weekly Game】
Brute Force/Adjacency Matrix Breadth First Directed Weighted Graph Undirected Weighted Graph
Charging effect simulation
multiplayer-hlap 包有问题,无法升级的解决方案
Drools basic introduction, introductory case, basic syntax
Layer 2 broadcast storm (cause + judgment + solution)
Is there a way to earn 300 yuan a day by doing a side business?
Gateway路由的配置方式
验证整数输入
Arbitrum 专访 | L2 Summer, 脱颖而出的 Arbitrum 为开发者带来了什么?
系统需求多变如何设计
What are the project management tools like MS Project
The comprehensive result of the case statement, do you know it?[Verilog Advanced Tutorial]
uniapp使用第三方字体