【树】637. 二叉树的层平均值

题目:

解答:

层次遍历过程种,进行操作。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<double> averageOfLevels(TreeNode* root) 
13     {
14         vector<double> result;
15 
16         if (root == NULL)
17         {
18             return result;
19         }
20 
21         queue<TreeNode*> q;
22         q.push(root);
23 
24         int count = 1;
25         int level = 0;
26         long sum_level = 0;
27 
28         // vector<int> tmp(0);
29         while(!q.empty())
30         {
31             // tmp.clear();
32             level = 0;
33             sum_level = 0;
34 
35             for (int i = 0; i < count; ++i)
36             {
37                 root = q.front();
38                 q.pop();
39                 sum_level = sum_level + root->val;
40 
41                 if (root->left != NULL)
42                 {
43                     q.push(root->left);
44                     ++level;
45                 }
46                 if (root->right != NULL)
47                 {
48                     q.push(root->right);
49                     ++level;
50                 }
51             }
52 
53             double avg = sum_level * 1.0 / count;
54             count = level;
55             result.push_back(avg);
56         }
57         //reverse(result.begin(), result.end());
58         return result;
59 
60     }
61 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12821855.html