题解 | #牛群平均重量#
牛群平均重量
https://www.nowcoder.com/practice/9b826d0a84034e8e8afd4c451f7d34e0
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return double浮点型vector */ vector<double> averageOfLevels(TreeNode* root) { // write code here vector<double> ans; queue<TreeNode*> q; if (root == nullptr) { return ans; } q.push(root); while (q.size()) { int num = q.size(); int sum = 0; int count = num; while (num--) { TreeNode* t = q.front(); sum += t->val; if (t->left) q.push(t->left); if (t->right) q.push(t->right); q.pop(); } ans.push_back(sum * 1.0 / count); } return ans; } };