Skip to content

Commit

Permalink
Merge pull request #133 from yuvaraja99/patch-4
Browse files Browse the repository at this point in the history
Created code average-of-levels-in-binary-tree.cpp
  • Loading branch information
Ayushsinhahaha authored Oct 30, 2022
2 parents 7af5dfa + a7f924c commit 7929b4e
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions code average-of-levels-in-binary-tree.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Given the root of a binary tree, return the average value of the nodes on each level in the form of an array.
*/

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;
vector<TreeNode *> q;
q.emplace_back(root);
while (!q.empty()) {
long long sum = 0, count = 0;
vector<TreeNode *> next_q;
for (const auto& n : q) {
sum += n->val;
++count;
if (n->left) {
next_q.emplace_back(n->left);
}
if (n->right) {
next_q.emplace_back(n->right);
}
}
swap(q, next_q);
result.emplace_back(sum * 1.0 / count);
}
return result;
}
};

0 comments on commit 7929b4e

Please sign in to comment.