515. Find Largest Value in Each Tree Row**
https://leetcode.com/problems/find-largest-value-in-each-tree-row/
题目描述
You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
C++ 实现 1
逻辑其实和 513. Find Bottom Left Tree Value** 没啥区别. 层序遍历.
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
int imax = q.front()->val;
while (size --) {
auto r = q.front();
q.pop();
imax = max(imax, r->val);
if (r->left) q.push(r->left);
if (r->right) q.push(r->right);
}
res.push_back(imax);
}
return res;
}
};
C++ 实现 2
这道题其实也可以用 DFS 来实现, 使用 d 来记录当前访问的深度; 如果 d == res.size(), 说明此时访问的是第 d 层的第一个节点 (就是说第一次到第 d 层), 将该节点的值加入到 res 中; 之后如果再到第 d, 那么更新 res[d] 即可.
class Solution {
private:
vector<int> res;
void dfs(TreeNode *root, int d) {
if (!root) return;
if (d == res.size()) res.push_back(root->val);
else res[d] = max(res[d], root->val);
dfs(root->left, d + 1);
dfs(root->right, d + 1);
}
public:
vector<int> largestValues(TreeNode* root) {
dfs(root, 0);
return res;
}
};
本文介绍了LeetCode上编号为515的问题“Find Largest Value in Each Tree Row”的解决方案。该问题要求在二叉树的每一层找到最大的数值。文章提供了两种C++实现方法,一种是基于层序遍历的解决方案,另一种是使用深度优先搜索(DFS)的方法。通过这两种方式,可以有效地解决该问题并返回每一层的最大值。

168

被折叠的 条评论
为什么被折叠?



