题目
原题在此
解析
标准的level order traversal, 没啥好讲的.
代码
c++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: vector<double> averageOfLevels(TreeNode* root) { if(!root) return {}; vector<double> res; queue<TreeNode*> q; q.push(root); while(!q.empty()) { int n = q.size(); long long sum = 0; for(int i = 0; i < n; ++i) { TreeNode* tmp = q.front(); q.pop(); sum += tmp->val; if(tmp->left) q.push(tmp->left); if(tmp->right) q.push(tmp->right); } res.push_back(double(sum) / double(n)); } return res; } };
|