問題(Easy):
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
- The range of node's value is in the range of 32-bit signed integer.
大意:
給出一個(gè)非空的二叉樹,以數(shù)組的形式返回每一層的節(jié)點(diǎn)平均值。
例1:
輸入:
輸出: [3, 14.5, 11]
解釋:
0層的平均值是3,1層的平均值是14.5,2層的平均值是11。所以返回 [3, 14.5, 11]。
注意:
- 節(jié)點(diǎn)值的范圍為32比特的有符號整型。
思路:
要計(jì)算每一層的平均值,肯定用BFS的遍歷方式了,使用一個(gè)隊(duì)列來遍歷二叉樹,同時(shí)用一個(gè)數(shù)來記錄每層的節(jié)點(diǎn)數(shù),遍歷隊(duì)列的過程中不斷把左右子節(jié)點(diǎn)加入到隊(duì)列后,同時(shí)增加記錄下一層數(shù)量的變量,且累加每個(gè)節(jié)點(diǎn)的值。遍歷完這一層應(yīng)有的節(jié)點(diǎn)數(shù)就可以計(jì)算該層的平均值了,都添加到一個(gè)數(shù)組中去即可。
需要注意的是節(jié)點(diǎn)值范圍比較大,需要用long型變量來記錄和。
代碼(C++):
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res;
if (root == NULL) return res;
queue<TreeNode> q;
q.push(*root);
int levelNum = 1;
while (!q.empty()) {
int temp = levelNum;
levelNum = 0;
long sum = 0;
for (int i = 0; i < temp; i++) {
TreeNode node = q.front();
q.pop();
sum = sum + node.val;
if (node.left != NULL) {
q.push(*node.left);
levelNum++;
}
if (node.right != NULL) {
q.push(*node.right);
levelNum++;
}
}
res.push_back((double)sum / (double)temp);
}
return res;
}
};
合集:https://github.com/Cloudox/LeetCode-Record