使用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) {
vector<int> result;
queue<TreeNode*> que;
if(root != nullptr){
que.push(root);
}
while(!que.empty()){
int size = que.size();
int maxNum = que.front()->val;
for(int i = 0; i < size; i++){
TreeNode * cur = que.front();
maxNum = max(maxNum, cur->val);
que.pop();
if(cur->left != nullptr){
que.push(cur->left);
}
if(cur->right != nullptr){
que.push(cur->right);
}
}
result.push_back(maxNum);
}
return result;
}
};