给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
示例 1:
输入:
3/ \9 20/ \15 7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
提示:
节点值的范围在32位有符号整数范围内。
代码如下:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<double> averageOfLevels(TreeNode* root) {auto cnt = vector<int>();auto sum = vector<double>();dfs(root,0,cnt,sum);auto ave = vector<double>();for (int i = 0;i<sum.size();i++){ave.push_back(sum[i]/cnt[i]);}return ave;}void dfs(TreeNode *root,int lev,vector<int>&cnt,vector<double>&sum){if (root==nullptr) return ;if (lev < sum.size()){sum[lev]+=root->val;cnt[lev]+=1;}else {sum.push_back(1.0*root->val);cnt.push_back(1);}dfs(root->left,lev+1,cnt,sum);dfs(root->right,lev+1,cnt,sum);}
};