Skip to content

Commit 70e35c1

Browse files
authored
Create 0637-average-of-levels-in-binary-tree.cpp
1 parent d88f4fc commit 70e35c1

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Diff for: cpp/0637-average-of-levels-in-binary-tree.cpp

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array.
3+
Answers within 10-5 of the actual answer will be accepted.
4+
5+
Ex. Input: root = [3,9,20,null,null,15,7]
6+
Output: [3.00000,14.50000,11.00000]
7+
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
8+
Hence return [3, 14.5, 11].
9+
10+
Time : O(N)
11+
Space : O(N)
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* struct TreeNode {
17+
* int val;
18+
* TreeNode *left;
19+
* TreeNode *right;
20+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
21+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
22+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
23+
* };
24+
*/
25+
class Solution {
26+
public:
27+
vector<double> averageOfLevels(TreeNode* root) {
28+
vector <double> v;
29+
if(root == NULL)
30+
return v;
31+
queue <TreeNode *> q;
32+
q.push(root);
33+
34+
while(!q.empty()) {
35+
double sum = 0, count = 0;
36+
int siz = q.size();
37+
for(int i = 0 ; i < siz ; i++) {
38+
sum += q.front() -> val;
39+
if(q.front() -> left)
40+
q.push(q.front() -> left);
41+
if(q.front() -> right)
42+
q.push(q.front() -> right);
43+
++count;
44+
q.pop();
45+
}
46+
v.push_back(sum / count);
47+
}
48+
return v;
49+
}
50+
};

0 commit comments

Comments
 (0)