当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
随机推荐
7-43 字符串关键字的散列映射 (25 分) 谜之测试点
# ODS及DWD层自动化构建##, 220731,
深度学习:目标检测入门知识
小程序(开发必备常识)1
程序员的七夕浪漫时刻
【LeetCode】206. Reverse linked list
Common SQL interview questions: 50 classic examples
JSP WebSehll 后门脚本
MySQL8.0.28 installation tutorial
MySQL8.0.26安装配置教程(windows 64位)
第二章——堆栈、队列
Kubernetes 基本概念
WebShell Feature Value Summary and Detection Tool
MySQL8--Windows下使用压缩包安装的方法
分布式事务解决方案模型
关于跨域问题
就瞎写=感想
(forwarded) HashCode summary (2)
深度自编码网络的集成学习ICPS入侵检测模型
JSP Webshell 免杀