-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path637-二叉树的层平均值.cpp
More file actions
36 lines (36 loc) · 958 Bytes
/
637-二叉树的层平均值.cpp
File metadata and controls
36 lines (36 loc) · 958 Bytes
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
34
35
36
/**
* 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 {
public:
vector<double> averageOfLevels(TreeNode* root) {
//只有一个节点
if(!root->left && !root->right)
return {root->val * 1.0};
//BFS
vector<double> res;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()){
long curSum = 0;
int len = que.size();
for(int i=0;i<len;i++){
TreeNode* cur = que.front();
que.pop();
curSum += cur->val;
if(cur->left)
que.push(cur->left);
if(cur->right)
que.push(cur->right);
}
res.push_back(curSum / (len * 1.0));
}
return res;
}
};