0%

637. Average of Levels in Binary Tree

题目

原题在此

解析

标准的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
/**
* 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) {
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;
}
};