一:题目
二:上码
/*** 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<double> averageOfLevels(TreeNode* root) {queue<TreeNode*> q;vector<double> ans;if(root) q.push(root);while(!q.empty()) {int size = q.size();//这里将队列的长度单独拿出来,q.size()是变化的 而我们统计每层double sum = 0; //的数字的时候,是不变的for(int i = 0; i < size; i++) {TreeNode* node = q.front();q.pop();sum += node->val;if(node->left) q.push(node->left);if(node->right) q.push(node->right);}ans.push_back(sum/size); }return ans;}
};