题目
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
思路
1、BFS。连续这几道题,思路都是一样的,只是根据要求输出的结果不同,做一些相应的改动,主干部分都类似。
2、简化写法。
实现方法
一、BFS
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(!root) return res;
queue<TreeNode*> q,tmp;
q.push(root);
while(!q.empty()){
int count=q.size();
//遍历一层,找到最大值
tmp=q;
int vmax=q.front()->val;
for(int i=0;i<count;i++){
vmax=max(vmax,tmp.front()->val);
tmp.pop();
}
res.push_back(vmax);
//将下一层的元素放入队列中
while(count>0){
TreeNode* top=q.front();
q.pop();
count--;
if(top->left) q.push(top->left);
if(top->right) q.push(top->right);
}
}
return res;
}
};
二、简化写法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int count=q.size();
int vmax=q.front()->val;
while(count--){
TreeNode* top=q.front();
q.pop();
if(top->val>vmax) vmax=top->val; //遍历时,直接判断大小,将最大的值保存下来
if(top->left) q.push(top->left);
if(top->right) q.push(top->right);
}
res.push_back(vmax);
}
return res;
}
};