当前位置:网站首页>365-day challenge LeetCode1000 questions - Day 044 Maximum element in the layer and level traversal
365-day challenge LeetCode1000 questions - Day 044 Maximum element in the layer and level traversal
2022-07-31 12:32:00 【ShowM3TheCode】
1161. 最大层内元素和

代码实现(自解)
/** * 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 maxSum = INT_MIN, maxLevel = 0;
queue<TreeNode*> _queue;
int curSum = 0, curLevel = 0, sz = 0;
TreeNode* curNode = NULL;
_queue.push(root);
while (!_queue.empty()) {
sz = _queue.size();
curSum = 0;
curLevel++;
while (sz--) {
curNode = _queue.front();
_queue.pop();
curSum += curNode->val;
if (curNode->left) _queue.push(curNode->left);
if (curNode->right) _queue.push(curNode->right);
}
if (curSum > maxSum) {
maxSum = curSum;
maxLevel = curLevel;
}
}
return maxLevel;
}
};
边栏推荐
猜你喜欢
随机推荐
Selenium自动化测试之Selenium IDE
系统集成项目管理工程师(软考中级)知识点总结【挣值分析】【关键路径】
初识QEMU
MySQL面试八股文(2022最新整理)
阿里三面:MQ 消息丢失、重复、积压问题,怎么解决?
MySQL日志中“binlog”的三种格式玩起来真爽
The 2nd activity of the TOGAF10 Standard Reading Club continues wonderfully, and the highlights will be reviewed!
CameraToolUnity中两种摄像机的两种观察控制方式
使用docker搭建mysql主从
分布式监视 Zabbix 和 Prometheus 到底怎么选?千万别用错了!
Three-Phase PWM Rectifier Predictive Direct Power Control
Full GC (Ergonomics)排查分析
Error EPERM operation not permitted, mkdir ‘Dsoftwarenodejsnode_cache_cacach两种解决办法
尚硅谷–MySQL–基础篇(P1~P95)
Comparison of ipv4 and ipv6 (IPV4)
基本语法(二)
sqlalchemy 判断一个array 类型的字段是否和一个array有至少一个一致的数据
关于我放弃考研这件事儿
vivado里那些看不懂的原语
跨境电商小知识之跨境电商物流定义以及方式讲解









