?
链接:剑指 Offer II 044. 二叉树每层的最大值
题解:
/**
* 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) {
vector<int> result;
if (!root) {
return result;
}
std::queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
int size = que.size();
int tmp = INT_MIN;
for (int i = 0; i < size; ++i) {
auto f = que.front();
que.pop();
if (f->left) {
que.push(f->left);
}
if (f->right) {
que.push(f->right);
}
tmp = max(tmp, f->val);
}
result.push_back(tmp);
}
return result;
}
};
|