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 @ 2024-07-22 00:46  Tomorrowland_D  阅读(10)  评论(0编辑  收藏  举报