当前位置:网站首页>力扣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;
}
};边栏推荐
猜你喜欢

The code is correct, and the rendering page does not display the reason

Libuv框架echo-server.c源码详解(TCP部分)

Rn7302 three-phase electric quantity detection (based on STM32 single chip microcomputer)

freeswitch设置最大呼叫时长

Online facing such an online world, the only limitation is our imagination

声网 VQA:将实时互动中未知的视频画质用户主观体验变可知

Freeswitch uses origin to dialplan

Freeswitch sets the maximum call duration

职场IT老鸟的几点小习惯

C language tutorial
随机推荐
Last 29 days
Niubi 666, this project makes web page making as simple as building blocks
Comprehensive analysis of real enterprise software testing process
CRC32概述以及实现和使用
KMP string
Libuv框架echo-server.c源码详解(TCP部分)
整型提升和大小端字节序
Interpretation of Blog
华为云计算之物理节点CNA安装教程
Build your jmeter+jenkins+ant
4~20mA输入/0~5V输出的I/V转换电路
Unity packaging webgl uses IIS to solve the error
声网 VQA:将实时互动中未知的视频画质用户主观体验变可知
Yolact++ pytoch environment
Servlet value passing JSP
Extern "C" overview
OpenGL API learning (2008) client server client server
Rust FFI 编程 - libc crate
【Rust翻译】从头实现Rust异步执行器
FPGA - 7 Series FPGA selectio -09- io of advanced logic resources_ FIFO