当前位置:网站首页>LeetCode:1161. 最大层内元素和【BFS层序遍历】
LeetCode:1161. 最大层内元素和【BFS层序遍历】
2022-08-02 03:11:00 【星空皓月】
题目描述
思路
用BFS层序遍历来写。当前队列个数就是当前层的节点个数。再压入下一层节点的同时,计算当前层内元素和。
AC代码
/** * 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) {
int ans = -1e9 + 7, pos = 1;
queue<TreeNode*> q;
q.push(root);
int level = 0;
while(!q.empty()) {
level++;
int size = q.size(), sum = 0;
// 一层一层计算
while(size -- > 0) {
TreeNode* cur = q.front(); q.pop();
sum += cur->val;
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
}
if(ans < sum) {
ans = sum;
pos = level;
}
}
return pos;
}
};
边栏推荐
猜你喜欢
随机推荐
CentOS7安装Oracle数据库的全流程
(转帖)HashCode总结(2)
mysql8.0.28下载和安装详细教程,适配win11
Go简单实现协程池
基于分布式随机森林的火电厂燃烧系统设备建模方法
7-40 奥运排行榜 (25 分)多项排序
2022年最新一篇文章教你青龙面板拉库,拉取单文件,安装依赖,设置环境变量,解决没有或丢失依赖can‘t find module之保姆教程(附带几十个青龙面板脚本仓库)
PHP WebSehll 后门脚本与检测工具
直击程序员面试现场:百度面试官都问了我些啥?
ROS2自学笔记:launch文件完整编写流程
5.合宙Air32F103_LCD_key
Navicat cannot connect to database Mysql because of WiFi
DVWA之SQL注入
ModuleNotFoundError: No module named ‘openpyxl‘
Reasons and solutions for Invalid bound statement (not found)
MySql中的like和in走不走索引
R16 Type II量化反馈码本的产生
2W字!详解20道Redis经典面试题!(珍藏版)
关于跨域问题
[LeetCode] 83. Delete duplicate elements in the sorted list