广度搜索
/**
* 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 {
private:
vector<double>ans;
public:
vector<double> averageOfLevels(TreeNode* root) {
if(!root) return ans;
queue<TreeNode *>q;
double tmp = 0;
int cnt = 0;
TreeNode* t = NULL;
q.push(root);
while(!q.empty())
{
tmp = 0;
cnt = 0;
queue<TreeNode*>q1;
while(!q.empty())
{
tmp += q.front()->val;
cnt++;
q1.push(q.front());
q.pop();
}
ans.push_back(tmp/cnt);
while(!q1.empty())
{
t = q1.front();
q1.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return ans;
}
};