- 二叉树的层平均值
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
示例 1:
输入:
3
/
9 20
/
15 7
输出:[3, 14.5, 11]
解释:
第 0 层的平均值是 3 , 第1层是 14.5 , 第2层是 11 。因此返回 [3, 14.5, 11] 。
方法一:深度优先搜索
使用深度优先搜索计算二叉树的层平均值,需要维护两个数组,counts 用于存储二叉树的每一层的节点数,sums 用于存储二叉树的每一层的节点值之和。搜索过程中需要记录当前节点所在层,如果访问到的节点在第 ii 层,则将counts[i] 的值加 1,并将该节点的值加到 sums[i]。
遍历结束之后,第 ii 层的平均值即为 sums[i]/counts[i]。
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/solution/er-cha-shu-de-ceng-ping-jun-zhi-by-leetcode-soluti/
/**
* 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 counts = vector<int>();
auto sum = vector<double>();
dfs(root, 0, counts, sum);
auto ave = vector<double>();
int size = sum.size();
for (int i = 0; i < size; i++) {
ave.push_back(sum[i] / counts[i]);
}
return ave;
}
void dfs(TreeNode * node, int level, vector<int>& counts, vector<double>& sum) {
if (node == nullptr) return;
if (level < sum.size()) {
sum[level] += node->val;
counts[level] += 1;
} else {
sum.push_back(node->val);
counts.push_back(1);
}
dfs(node->left, level + 1, counts, sum);
dfs(node->right, level + 1, counts, sum);
}
};