题目链接515. 在每个树行中找最大值 - 力扣(LeetCode)
实现思路使用层序遍历,记录每一行的最大值即可。
q.push(root);
while (!q.empty()) {
int size = q.size();
int max = INT_MIN;
for (int i = 0; i < size; i++) {
TreeNode * temp = q.front();
q.pop();
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
max = temp->val > max ? temp->val : max;
}
ans.push_back(max);
}
实现代码(C++)
class Solution {
public:
vector largestValues(TreeNode* root) {
if (root == nullptr) {
return vector();
}
vector ans;
queue q;
q.push(root);
while (!q.empty()) {
int size = q.size();
int max = INT_MIN;
for (int i = 0; i < size; i++) {
TreeNode * temp = q.front();
q.pop();
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
max = temp->val > max ? temp->val : max;
}
ans.push_back(max);
}
return ans;
}
};



