-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAverageOfLevelsInBinaryTree.cpp
49 lines (43 loc) · 1.38 KB
/
AverageOfLevelsInBinaryTree.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int 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) {}
* };
*/
class Solution {
public:
void Inorder(TreeNode* root, vector<vector<int>> *Sol, int Level) {
if (root == NULL) {
return;
}
if (Level == Sol->size()) {
Sol->push_back({});
}
Inorder(root->left, Sol, Level+1);
Sol->at(Level).push_back(root->val);
Inorder(root->right, Sol, Level+1);
}
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> Sol;
Inorder(root, &Sol, 0);
return Sol;
}
vector<double> averageOfLevels(TreeNode* root) {
vector<vector<int>> Traversal = levelOrder(root);
vector<double> Sol;
for(int i=0; i<Traversal.size(); i++){
double Sum = 0;
for(int j=0; j<Traversal[i].size(); j++){
Sum += Traversal[i][j];
}
Sum /= Traversal[i].size();
Sol.push_back(Sum);
}
return Sol;
}
};