题目:
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
- The range of node's value is in the range of 32-bit signed integer.
分析:
题目很好理解,就是求二叉树每一层的平均值。
我们可以创建一个用来存储每层节点值和的数组,和一个存储每层节点个数的数组,通过递归的方式来求二叉树的层平均值,注意在求当前层时要判断层数是否超过了数组的大小,一旦超过,就要扩大数组,一遍存储当前层的信息。
程序:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
getAverage(root, res, );
for(int i = ; i < res.size(); ++i){
res[i] /= nums[i];
}
return res;
}
void getAverage(TreeNode* root, vector<double> &res, int level){
if(root == nullptr) return;
if(level >= res.size()){
res.push_back();
nums.push_back();
}
res[level] += root->val;
nums[level]++;
getAverage(root->left, res, level+);
getAverage(root->right, res, level+);
}
private:
vector<double> res;
vector<int> nums;
};