Leetcode 637. 二叉树的层平均值
层序遍历
/**
* 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<double> averageOfLevels(TreeNode* root) {
layerorder(root);
return average();
}
private:
struct node{
double total = 0;
int count = 0;
};
vector<node> layer;
void layerorder(TreeNode* root){
queue<TreeNode*> q;
queue<int> lay;
if(root==NULL) return;
q.push(root);
lay.push(0);
while(q.empty()==false){
TreeNode* front = q.front();
q.pop();
int level = lay.front();
lay.pop();
if(front->left!=NULL){
q.push(front->left);
lay.push(level+1);
}
if(front->right!=NULL){
q.push(front->right);
lay.push(level+1);
}
if(layer.size()<level+1){
node a = node();
layer.push_back(a);
}
layer[level].total +=front->val;
layer[level].count +=1;
}
return;
}
vector<double> average(){
vector<double> aver;
for(int i = 0;i<layer.size();i++){
aver.push_back(layer[i].total/layer[i].count);
}
return aver;
}
};