1.题目描述
2.题解
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
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;
queue<TreeNode*> que;
if(root != nullptr) que.push(root);
while(!que.empty()) {
int size = que.size();
int maxValue = INT_MIN;
for(int i = 0; i < size; i++) {
TreeNode* cur = que.front();
que.pop();
maxValue = cur->val > maxValue ? cur->val : maxValue; // 求出每层的最大值并保存在result数组中
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
result.push_back(maxValue);
}
return result;
}
};
|