解题思路:
BFS遍历每一层,统计每一层的最大值放入数组中,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if(root == nullptr) return {};
queue<TreeNode*> q;
q.emplace(root);
vector<int> ans;
while(!q.empty()) {
int n = q.size();
int maxNum = INT_MIN;
for(int i = 0; i < n; i ++) {
TreeNode* node = q.front();
q.pop();
maxNum = max(maxNum, node->val);
if(node->left != nullptr) q.emplace(node->left);
if(node->right != nullptr) q.emplace(node->right);
}
ans.emplace_back(maxNum);
}
return ans;
}
};