Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created code average-of-levels-in-binary-tree.cpp #133

Merged
merged 1 commit into from
Oct 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
};