# 515. 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]
``````

``````class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if (!root) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int n = q.size(), mx = INT_MIN;
for (int i = 0; i < n; ++i) {
TreeNode *t = q.front(); q.pop();
mx = max(mx, t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(mx);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if (!root) return {};
vector<int> res;
helper(root, 1, res);
return res;
}
void helper(TreeNode* root, int depth, vector<int>& res) {
if (depth > res.size()) res.push_back(root->val);
else res[depth - 1] = max(res[depth - 1], root->val);
if (root->left) helper(root->left, depth + 1, res);
if (root->right) helper(root->right, depth + 1, res);
}
};
``````

https://discuss.leetcode.com/topic/79241/simple-and-easy-understand-c-dfs-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation