637. 二叉树的层平均值

给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.

示例 1:

输入:
3
/
9 20
/
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
注意:

节点值的范围在32位有符号整数范围内。

 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       vector<double> result;
14         if(root)
15         {
16           queue<TreeNode*> q;
17           q.push(root);
18           while(!q.empty())
19           {
20             int size = q.size();
21             int num = size;
22             double count = 0;
23             while(size--)
24             {
25               TreeNode* node = q.front();
26               q.pop();
27               if(node->left)q.push(node->left);
28               if(node->right)q.push(node->right);
29               count +=node->val;
30             }
31             result.push_back(count/num);
32           }
33         }
34       return result;
35     }
36 };

本质还是层次遍历,注意每行的结果可能会溢出,因此用double

原文地址:https://www.cnblogs.com/Swetchine/p/11361355.html