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;
}
};