File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < vector>
2
+ #include < stack>
3
+ using namespace std ;
4
+
5
+ struct TreeNode {
6
+ int val;
7
+ TreeNode *left;
8
+ TreeNode *right;
9
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
10
+ };
11
+
12
+ class Solution {
13
+ public:
14
+ vector<double > averageOfLevels (TreeNode* root) {
15
+ if (root==NULL ) return {};
16
+ stack<TreeNode*> s_parent;
17
+ stack<int > s_depth;
18
+ vector<double > sums;
19
+ vector<int > counts;
20
+
21
+ s_parent.push (root);
22
+ s_depth.push (1 );
23
+ while (!s_parent.empty ()){
24
+ TreeNode* tmp_node = s_parent.top (); s_parent.pop ();
25
+ int tmp_depth = s_depth.top (); s_depth.pop ();
26
+
27
+ if (tmp_depth>(int )sums.size ()){
28
+ sums.push_back ((double )(tmp_node->val ));
29
+ counts.push_back (1 );
30
+ }
31
+ else {
32
+ sums[tmp_depth-1 ] += (double )(tmp_node->val );
33
+ counts[tmp_depth-1 ] += 1 ;
34
+ }
35
+
36
+ if (tmp_node->right ){
37
+ s_parent.push (tmp_node->right );
38
+ s_depth.push (tmp_depth+1 );
39
+ }
40
+ if (tmp_node->left ){
41
+ s_parent.push (tmp_node->left );
42
+ s_depth.push (tmp_depth+1 );
43
+ }
44
+ }
45
+
46
+ for (int i = 0 ; i < (int )sums.size (); ++i) {
47
+ sums[i] /= counts[i];
48
+ }
49
+
50
+ return sums;
51
+ }
52
+ };
You can’t perform that action at this time.
0 commit comments