深度优先遍历
- 思路:
- 使用深度优先搜索计算二叉树的层平均值,维护两个数组用于统计各层节点和、各层节点个数;
- 递归统计时,需要传入当前统计深度;
cpp
/**
* 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 = std::vector<int>();
auto sums = std::vector<double>();
dfs(root, 0, counts, sums);
int size = sums.size();
auto averages = std::vector<double>();
for (int i = 0; i < size; ++i) {
averages.push_back(sums[i] / counts[i]);
}
return averages;
}
void dfs(TreeNode* root, int depth, std::vector<int>& counts, std::vector<double>& sums) {
if (root == nullptr) {
return;
}
if (depth < sums.size()) {
sums[depth] += root->val;
counts[depth] += 1;
} else {
sums.push_back(1.0 * root->val);
counts.push_back(1);
}
dfs(root->left, depth + 1, counts, sums);
dfs(root->right, depth + 1, counts, sums);
}
};