当前位置:网站首页>力扣515.在每棵树行中找最大值
力扣515.在每棵树行中找最大值
2022-06-28 06:55:00 【Base-Case】
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
示例2:
输入: root = [1,2,3]
输出: [1,3]
提示:
二叉树的节点个数的范围是 [0,104]
-231 <= Node.val <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-largest-value-in-each-tree-row
思路:一个简单的层序遍历
/**
* 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:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode*> q;
vector<int> ans;
int mx;
if(root!=NULL) q.push(root);
while(q.size()){
int len = q.size();//获取当层的长度
TreeNode *t = q.front();
mx=t->val;
for(int i=0;i<len;i++){
mx=max(t->val,mx);
if(t->left) q.push(t->left);//判断有无左孩子
if(t->right) q.push(t->right);//判断有无右孩子
q.pop();
t=q.front();
}
ans.push_back(mx);
}
return ans;
}
};
边栏推荐
- ROS rviz_ Satellite function package visualizes GNSS track and uses satellite map
- Niubi 666, this project makes web page making as simple as building blocks
- 未来互联网人才还稀缺吗?哪些技术方向热门?
- Trie string statistics
- AttributeError: 'callable_iterator' object has no attribute 'next'
- 5-minute NLP: summary of time chronology from bag of words to transformer
- JS of learning notes -- split(), replace(), join()
- Linux MySQL implements root user login without password
- [rust daily] May 24, 2020 rush, rocket, Mun, caspin
- FPGA - 7 Series FPGA selectio -09- io of advanced logic resources_ FIFO
猜你喜欢
JDBC learning (I) -- implementing simple CRUD operations
强化学习——格子世界
全方位透析真实企业软件测试流程
我的MVVM开源项目《出行防疫App》已发布
最后的二十九天
freeswitch设置最大呼叫时长
推荐几款0代码、免费、现学现用的可视化工具
Reinforcement learning - grid world
Voice network VQA: make the user's subjective experience of unknown video quality in real-time interaction known
Compilation principles final review
随机推荐
Singleton singleton mode
MySQL (I) - Installation
Alert pop-up processing in Web Automation
Pytorch RNN learning notes
Integer promotion and size side byte order
VM332 WAService.js:2 Error: _vm.changeTabs is not a function报错
选拔赛题目代码
[rust daily] May 24, 2020 rush, rocket, Mun, caspin
小程序页面设置100%高度还是留白怎么办?
C语言教程大全
Techo day Tencent technology open day, June 28 online waiting for you!
实现这个 issue 得700块钱人民币,有人做嘛?
职场IT老鸟的几点小习惯
Yolov5 adds a small target detection layer
微信小程序分页功能,下拉刷新功能,直接干货拿来就用
[online tutorial] official iptables tutorial -- learning notes 1
Tryout title code
普歌--三大基础排序,冒泡·选择·快速
js正则表达式系统讲解(全面的总结)
我的MVVM开源项目《出行防疫App》已发布