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 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 class Solution 18 { 19 public: 20 vector<double> averageOfLevels(TreeNode* root) 21 { 22 queue<TreeNode*> q; 23 TreeNode* p=root; 24 q.push(p); 25 vector<double> res; 26 while(!q.empty()) 27 { 28 int sz=q.size(); 29 double sum=0.0; 30 for(int i=0;i<sz;i++) 31 { 32 p=q.front(); 33 sum+=p->val; 34 if(p->left!=NULL) 35 q.push(p->left); 36 if(p->right!=NULL) 37 q.push(p->right); 38 q.pop(); 39 } 40 res.push_back(sum/sz); 41 } 42 return res; 43 } 44 };
层次遍历,问题不大