当前位置:网站首页>LeetCode 1161.最大层内元素和:层序遍历
LeetCode 1161.最大层内元素和:层序遍历
2022-07-31 10:55:00 【Tisfy】
【LetMeFly】1161.最大层内元素和
力扣题目链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree/
给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层,而根节点的子节点位于第 2 层,依此类推。
请返回层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。
示例 1:

输入:root = [1,7,0,7,-8,null,null] 输出:2 解释: 第 1 层各元素之和为 1, 第 2 层各元素之和为 7 + 0 = 7, 第 3 层各元素之和为 7 + -8 = -1, 所以我们返回第 2 层的层号,它的层内元素之和最大。
示例 2:
输入:root = [989,null,10250,98693,-89388,null,null,null,-32127] 输出:2
提示:
- 树中的节点数在
[1, 104]范围内 -105 <= Node.val <= 105
方法一:层序遍历 + 广搜BFS
有关二叉树的层序遍历,之前已经讲过,详细方法可参考 LeetCode 0107.二叉树的层序遍历II の 题解
本题,同样地,我们使用优先队列来对二叉树进行层序遍历。
- 用变量
maxSum记录当前的单层最大和 - 用变量
ans来记录取得maxSum的最小层号 - 用变量
nowLayer记录当前遍历到的层的层号
初始值maxSum为int范围内的最小值INT_MIN,ans取任意值即可,nowLayer的值取1。
在遍历到某一层时,用一个临时变量thisSum统计这一层的节点值之和
如果这一层遍历结束后,thisSum的值大于之前所记录的最大值maxSum
那么就更新maxSum为thisSum,并将ans赋值为当前层号nowLayer。
- 时间复杂度 O ( N ) O(N) O(N),其中 N N N是节点个数。
- 空间复杂度 O ( N 2 ) O(N2) O(N2),其中 N 2 N2 N2是节点最多的一层的节点数。
AC代码
C++
class Solution {
public:
int maxLevelSum(TreeNode* root) {
int maxSum = INT_MIN;
int ans = -1;
int nowLayer = 1;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int thisLayerNum = q.size(); // 这一层有几个元素
int thisSum = 0;
for (int i = 0; i < thisLayerNum; i++) {
TreeNode* thisNode = q.front();
q.pop();
thisSum += thisNode->val;
if (thisNode->left)
q.push(thisNode->left);
if (thisNode->right)
q.push(thisNode->right);
}
if (thisSum > maxSum) {
maxSum = thisSum;
ans = nowLayer;
}
nowLayer++;
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/126082726
边栏推荐
猜你喜欢

Intranet Penetration Learning (IV) Domain Lateral Movement - SMB and WMI Service Utilization

《云原生的本手、妙手和俗手》——2022全国新高考I卷作文

Redis缓冲穿透和缓冲击穿工具类的封装

可以用聚酯树脂将接线板密封接线盒吗?(接线盒灌封胶用哪种树脂)

Summary of three methods for SQL deduplication

3D激光SLAM:LeGO-LOAM论文解读---点云分割部分

Redis缓存面临的缓存击穿问题

Three ways of single sign-on

unity computeshader的可读写buffer

darknet 源码阅读笔记-01-activation_kernels.cu
随机推荐
Single sign-on principle and implementation
Sql优化总结!详细!(2021最新面试必问)
【Go事】一眼看穿 Go 的集合和切片
Deletion of the sequence table
Redis缓存面临的缓存穿透问题
使用内存映射加快PyTorch数据集的读取
细讲DDD领域驱动设计
Mybaits Frequently Asked Questions Explained
3D激光SLAM:LeGO-LOAM论文解读---点云分割部分
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文
Find a Go job in 7 days, Conditional statements to learn in Gopher, loop statements, Part 3
SQL - Left join, Right join, Inner join
nodeJs--url模块
darknet 训练分类网络
7 天能找到 Go 工作吗?学学 Go 数组和指针试试
Web系统常见安全漏洞介绍及解决方案-CSRF攻击
Experience innovation and iteration through the development of a lucky draw applet
Simple understanding of GCD
内网渗透学习(四)域横向移动——SMB和WMI服务利用
【LeetCode】141.环形链表