題目:
給定一個二元樹,回傳其每一層的平均值。
範例:
範例 1:
輸入:
3
/ \
9 20
/ \
15 7
輸出:[3.00000, 14.50000, 11.00000]
範例 2:
輸入:
1
/ \
2 3
/ \ \
4 5 6
輸出:[1.00000, 2.50000, 5.00000]
這題要計算每層的平均,那麼就很適合使用BFS方式來解題,因為BFS就是廣度優先逐層搜尋,然後順便計算每層的平均值
/**
* 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) {
vector<double> res;
if (root == nullptr)
return res;
queue<TreeNode*> queue;
queue.push(root);
while (!queue.empty()) {
int levelSize = queue.size();
double levelSum = 0;
for (int i = 0; i < levelSize; i++) {
TreeNode* curr = queue.front();
queue.pop();
levelSum += curr->val;
if (curr->left != nullptr)
queue.push(curr->left);
if (curr->right != nullptr)
queue.push(curr->right);
}
res.push_back(levelSum / levelSize);
}
return res;
}
};
參考:
#637. Average of Levels in Binary Tree