Leetcode 637. Average of Levels in Binary Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Average of Levels in Binary Tree

2. Solution

  • Version 1
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
37
38
39
40
41
42
43
44
45
/**
* 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) {
vector<double> result;
if(!root) {

}
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
double sum = 0;
int count = 0;
while(!q.empty()) {
TreeNode* current = q.front();
q.pop();
if(current) {
count++;
sum += current->val;
if(current->left) {
q.push(current->left);
}
if(current->right) {
q.push(current->right);
}
}
else if(count){
double mean = sum / count;
sum = 0;
count = 0;
result.push_back(mean);
q.push(nullptr);
}
}
return result;
}
};
  • Version 2
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
37
38
/**
* 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) {
vector<double> result;
if(!root) {
return result;
}
queue<TreeNode*> q;
q.push(root);
double sum = 0;
while(!q.empty()) {
sum = 0;
int size = q.size();
for(int i = 0; i < size; i++) {
TreeNode* current = q.front();
q.pop();
sum += current->val;
if(current->left) {
q.push(current->left);
}
if(current->right) {
q.push(current->right);
}
}
result.push_back(sum / size);
}
return result;
}
};

Reference

  1. https://leetcode.com/problems/average-of-levels-in-binary-tree/description/
如果有收获,可以请我喝杯咖啡!