-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAverageOfLevelsInABinaryTree.cpp
65 lines (53 loc) · 1.45 KB
/
AverageOfLevelsInABinaryTree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <queue>
struct TreeNode {
long val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
std::vector<double> AverageOfLevels() {
TreeNode* root;
std::queue<TreeNode*> nodeQueue;
std::vector<double> averageOfLevels = {1};
nodeQueue.push(root);
int total;
int layer = 0;
TreeNode* currNode;
// One level per while loop
while(nodeQueue.size() > 0) {
total = 0;
// One node per for loop, all nodes in level
for(int i = 0; i < (int)averageOfLevels[layer]; i++) {
// Set current node
currNode = nodeQueue.front();
// Add total
total += currNode->val;
// Add children
if(currNode->left != nullptr) {
if(averageOfLevels.size() - 1 == layer) {
averageOfLevels.push_back(0);
}
nodeQueue.push(currNode->left);
averageOfLevels[layer+1] += 1;
}
if(currNode->right != nullptr) {
if(averageOfLevels.size() - 1 == layer) {
averageOfLevels.push_back(0);
}
nodeQueue.push(currNode->right);
averageOfLevels[layer+1] += 1;
}
// Pop queue
nodeQueue.pop();
}
averageOfLevels[layer] = total/averageOfLevels[layer];
layer++;
}
return averageOfLevels;
}
int main() {
return 0;
}