LeetCode515.在每个树行中找最大值

力扣题目链接:https://leetcode.cn/problems/find-largest-value-in-each-tree-row/description/

题目叙述:

您需要在二叉树的每一行中找到最大的值。

思路

这题依旧是采用层序遍历的模板,只不过我们不需要设置current数组,并且需要设置一个maxVal找到每一层的最大值,在遍历每一层的过程中,更新这个最大值即可!

如果不会层序遍历的话,可以翻看我之前的文章,里面详细讲述了如何模拟层序遍历的过程!

二叉树的层序遍历:https://www.cnblogs.com/Tomorrowland/articles/18314740

AC代码如下:

class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if (root == NULL) return result;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
//定义maxVal,用来找到每一层的最大值
int maxVal = INT_MIN;
for (int i = 0; i < size; i++) {
TreeNode* current = que.front();
que.pop();
//在每一层的遍历过程中找到这一层的最大值
maxVal = current->val > maxVal ? current->val : maxVal;
if (current->left != NULL) que.push(current->left);
if (current->right != NULL) que.push(current->right);
}
//将最大的节点放入数组中即可
result.push_back(maxVal);
}
return result;
}
};
posted @   Tomorrowland_D  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示