当前位置:网站首页>LeetCode·每日一题·1161.最大层内元素和·层次遍历
LeetCode·每日一题·1161.最大层内元素和·层次遍历
2022-07-31 13:22:00 【小迅想变强】
链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree/solution/by-xun-ge-v-k02i/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目

示例

思路
解题思路
对于树的相关问题使用递归基本上都可以解决
对于本题我们需要寻找层内元素之和 最大 的那几层(可能只有一层)的层号,并返回其中 最小 的那个。
那么首先需要对每一层的元素进行遍历求和,对于树的每一层元素遍历,无疑使用层次遍历最为方便,对于层次遍历可以用递归也可以使用迭代,对于层次遍历迭代更方便理解,这里使用迭代实现层次遍历
具体实现
树的层次遍历需要使用队列保存每一层的元素,我们遍历树,将树的每一层元素存入队列,然后按每层弹出队列中元素,同时保存每层元素的和,并且判断弹出元素是否存在子节点,存在子节点时存入队列,每层弹出后保存最大值和对应层数
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxLevelSum(struct TreeNode* root){
struct TreeNode * ans[10000];//队列
int left = 0;
int right = 0;
ans[right++] = root;//头结点入队
int max = INT_MIN;//最大值层和
int storey = 1;//当前位于第几层
int s = -1;//最大值位于第几层
while(left < right)//层次遍历
{
int sum = 0;//当前层元素和
int r = right;
while(left < r)//按层弹出元素
{
sum += ans[left]->val;
if(ans[left]->left)//弹出元素判断是否存在子元素
{
ans[right++] = ans[left]->left;
}
if(ans[left]->right)
{
ans[right++] = ans[left]->right;
}
left++;
}
if(sum > max)//保存最大值层
{
max = sum;
s = storey;
}
storey++;
}
return s;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/maximum-level-sum-of-a-binary-tree/solution/by-xun-ge-v-k02i/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。时间空间复杂度

边栏推荐
- SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块
- C# using NumericUpDown control
- C# List用法 List介绍
- [CPU Design Practice] Simple Pipeline CPU Design
- 百度网盘安装在c盘显示系统权限限制的解决方法
- The latest complete code: Incremental training using the word2vec pre-training model (two loading methods corresponding to two saving methods) applicable to various versions of gensim
- VU 非父子组件通信
- 报错:npm ERR code EPERM
- C#中+=的用法
- [RPI]树莓派监控温度及报警关机保护「建议收藏」
猜你喜欢

C#使用ComboBox控件

Reasons and solutions for Invalid bound statement (not found)

百度网盘安装在c盘显示系统权限限制的解决方法

浏览器被hao360劫持解决办法

3.爬虫之Scrapy框架1安装与使用

How to quickly split and merge cell data in Excel

C#控件CheckBox的使用

Invalid bound statement (not found)出现的原因和解决方法

pytorch gpu版本安装最新

IDEA版Postman插件Restful Fast Request,细节到位,功能好用
随机推荐
SAP message TK 248 solved
IDEA连接MySQL数据库并执行SQL查询操作
STM32——软件SPI控制AD7705[通俗易懂]
Even if the image is missing in a large area, it can also be repaired realistically. The new model CM-GAN takes into account the global structure and texture details
FastAPI encapsulates a generic response
C#中+=的用法
C#Assembly的使用
机器学习模型验证:被低估的重要一环
SAP 电商云 Spartacus UI 和 Accelerator UI 里的 ASM 模块
CodeIgniter 打开错误日志
CentOS7 installation MySQL graphic detailed tutorial
【牛客刷题-SQL大厂面试真题】NO3.电商场景(某东商城)
C# List用法 List介绍
matlab as(assert dominance)
EXCEL如何快速拆分合并单元格数据
The latest complete code: Incremental training using the word2vec pre-training model (two loading methods corresponding to two saving methods) applicable to various versions of gensim
Solution for browser hijacking by hao360
爱可可AI前沿推介(7.31)
The operator,
PHP Serialization: eval