-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #133 from yuvaraja99/patch-4
Created code average-of-levels-in-binary-tree.cpp
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |