0%

average-of-levels-in-binary-tree

Average of Levels in Binary Tree – LeetCode 637

Problem

Description

Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.

Answer

Original

Code

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
/**
* 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> ans;
queue<TreeNode*> q;
q.push(root);
unsigned S;
double level;
TreeNode *now;
while(!q.empty()){
S = q.size();
level = 0.0;
for(int i = 0; i != S; ++i){
level += q.front()->val;
if(q.front()->left) q.push(q.front()->left);
if(q.front()->right) q.push(q.front()->right);
q.pop();
}
ans.emplace_back(level / S);
}
return ans;
}
};

思路

简单的BFS。时间复杂度$O(n)$,空间复杂度$O(m)$。
耗时$8$ ms,排名$0.70\%$