您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
/**
* 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> res;
if(root == nullptr) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int levelSize = q.size();
int max_val = q.front()->val;
for(int i=0;i<levelSize;i++){
TreeNode* cur = q.front();
max_val = max(max_val, cur->val);
q.pop();
if(cur->left){
q.push(cur->left);
}
if(cur->right) {
q.push(cur->right);
}
}
res.push_back(max_val);
}
return res;
}
};