Skip to content

Commit 3d817db

Browse files
Add files via upload
1 parent c4b682c commit 3d817db

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Runtime: 20 ms, faster than 69.74% of C++ online submissions for Average of Levels in Binary Tree.
2+
// Memory Usage: 21.7 MB, less than 77.78% of C++ online submissions for Average of Levels in Binary Tree.
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution
14+
{
15+
public:
16+
vector<double> averageOfLevels(TreeNode* root)
17+
{
18+
vector<double> res;
19+
if (root == nullptr)
20+
return res;
21+
22+
queue<TreeNode*> memo;
23+
memo.push(root);
24+
25+
while (!memo.empty())
26+
{
27+
double size = memo.size();
28+
double temp = 0;
29+
30+
for (int i = memo.size(); i > 0; --i)
31+
{
32+
root = memo.front();
33+
memo.pop();
34+
35+
temp += root->val;
36+
37+
if (root->left) memo.push(root->left);
38+
if (root->right) memo.push(root->right);
39+
}
40+
41+
res.push_back(temp / size);
42+
}
43+
return res;
44+
}
45+
};

0 commit comments

Comments
 (0)