?题目描述
给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
注意:
节点值的范围在32位有符号整数范围内。
?Method 1: DFS , preorderTraversal_recursive
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// DFS做法,先序遍历
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
if (root == nullptr) { return {};} // C++11新标准推荐nullptr
//由于节点值的范围在32位有符号整数范围,所以求和用longlong保险起见↓
vector<pair<long long,int>> sum_count; //把两个数组合成一个pair vector↓
vector<double> ans;
preorder(root, 0, sum_count);
// dfs递归处理完之后,才能知道每一层的sum和count,才能进行下面最终的操作
// 而第二种方法 bfs不需要递归,一层一层做
for (const auto &p : sum_count) { // "range-based for-loops".
// C++11新标准推荐static_cast<double>()类型转换
ans.push_back(static_cast<double>(p.first) / p.second);
}
return ans;
}
private:
void preorder(TreeNode* root,int depth,vector<pair<long long,int>> &sum_count){
if (root == nullptr) return;
if (depth >= sum_count.size()) sum_count.push_back({0,0}); //因为sum_count没有初始化和构造过,所以动态的去更新它
sum_count[depth].first += root->val; // 每一层的和
++sum_count[depth].second; //每一层节点个数
preorder(root->left, depth + 1, sum_count);
preorder(root->right, depth + 1, sum_count);
}
};
?Method 2: BFS 的话就不需要递归,一个while循环就可以, 不断创建你下一层要访问的节点
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//BFS
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
if(root == nullptr) return {};
vector<double> ans;
vector<TreeNode*> curr, next; // 当前节点,下一层节点
curr.push_back(root);
// process every leverl one by one
// BFS 的话就不需要递归,一个while循环就可以了,不断创建你下一层要访问的节点
while (!curr.empty()) {
long long sum = 0;
for (const auto &node:curr) {
sum += node->val;
if (node->left) next.push_back(node->left); //如果当前节点有左节点,就将它加入next
if (node->right) next.push_back(node->right);
}
ans.push_back(static_cast<double>(sum) / curr.size());
//swap 不涉及复制,相当于把内部的指针对调一下,curr指向next之前指向的区域。
curr.swap(next);
next.clear();
}
return ans;
}
};