当前位置:网站首页>LeetCode-515. Find the maximum value in each tree row
LeetCode-515. Find the maximum value in each tree row
2022-06-27 05:17:00 【Border wanderer】
Given the root node of a binary tree root , Please find the maximum value of each layer in the binary tree .
Example 1:
Input : root = [1,3,2,5,3,null,9]
Output : [1,3,9]
Example 2:
Input : root = [1,2,3]
Output : [1,3]
Tips :
The range of the number of nodes in a binary tree is [0,104]
-231 <= Node.val <= 231 - 1
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
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) {
if (!root) {
return {};
}
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int len = q.size();
int maxVal = INT_MIN;
while (len--) {
TreeNode* t = q.front();
q.pop();
maxVal = maxVal > t->val ? maxVal : t->val;
if (t->left) {
q.push(t->left);
}
if (t->right) {
q.push(t->right);
}
}
res.push_back(maxVal);
}
return res;
}
};
边栏推荐
猜你喜欢
Microservice system design -- distributed transaction service design
齐纳二极管 稳压二极管 SOD123封装 正负区分
leetcode-20. Valid parentheses -js version
Cognition - how to fill in 2022 college entrance examination volunteers
Golang Hello installation environment exception [resolved]
使用域名转发mqtt协议,避坑指南
导航【机器学习】
微信小程序WebSocket使用案例
双位置继电器RXMVB2 R251 204 110DC
快速排序(非遞歸)和歸並排序
随机推荐
微信小程序WebSocket使用案例
Microservice system design -- microservice invocation design
neo4j数据库导出
stm32读取IO高低电平状态
Microservice system design - service fusing and degradation design
清华大学开源软件镜像站网址
机械转码日记【17】模板,STL简介
Py2neo basic syntax
微服务系统设计——服务注册与发现和配置设计
jq怎么获取元素的id名
017 basics of C language: bit field and typedef
Discussion on streaming media protocol (MPEG2-TS, RTSP, RTP, RTCP, SDP, RTMP, HLS, HDS, HSS, mpeg-dash)
《数据库原理与应用》第一版 马春梅……编著 期末复习笔记
微服务系统设计——微服务调用设计
快速排序(非递归)和归并排序
【B站UP DR_CAN学习笔记】Kalman滤波3
Ad22 Gerber files Click to open the Gerber step interface. Official solutions to problems
012 C language foundation: C array
Microservice system design -- distributed lock service design
差点因为 JSON.stringify 丢了奖金...