刷题-力扣-515. 在每个树行中找最大值
作者:互联网
515. 在每个树行中找最大值
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/ \
3 2
/ \ \
5 3 9
示例2:
输入: root = [1,2,3]
输出: [1,3]
解释:
1
/ \
2 3
示例3:
输入: root = [1]
输出: [1]
示例4:
输入: root = [1,null,2]
输出: [1,2]
解释:
1
\
2
示例5:
输入: root = []
输出: []
提示:
- 二叉树的节点个数的范围是 [0,104]
- -231 <= Node.val <= 231 - 1
题目分析
- 根据题目描述获取树中每一层的最大值
- 广度优先搜索遍历
代码
/**
* 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) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> nodeList;
nodeList.emplace(root);
while (!nodeList.empty()) {
int max = nodeList.front()->val;
int nodeListLen = nodeList.size();
for (int i = 0; i < nodeListLen; ++i) {
max = max > nodeList.front()->val ? max : nodeList.front()->val;
if (nodeList.front()->left) nodeList.emplace(nodeList.front()->left);
if (nodeList.front()->right) nodeList.emplace(nodeList.front()->right);
nodeList.pop();
}
res.emplace_back(max);
}
return res;
}
};
标签:right,nodeList,root,力扣,front,TreeNode,515,树行,left 来源: https://www.cnblogs.com/HanYG/p/15155460.html