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:
3
/ \
9 20
/ \
15 7
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.
思路:用隊列實現按層遍歷二叉樹.關鍵是如何確定哪些結點在同一層.用隊列解決:從根開始往下,每次往隊列中填充一層的node,第一次即根root,然后計算此時隊列大小count,這就是第一層的節點數.for循環處理第一層所有結點,將其左右子節點入棧(若存在的話),并累加該節點的val,循環結束后計算第一層的平均值.此時隊列中全部為第二層的結點.依此類推,記第二層結點數為n2,從隊列中彈出兩個隊首元素做處理,然后將第三層結點入隊尾......直至隊列為空.
/**
* 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) {
queue<TreeNode*> q;//結點隊列
vector<double> result;
q.push(root);//從根開始
while (!q.empty()) {
int count = q.size();//記錄該層大小
double sum = 0.0;//累加和
for (int i = 0; i < count; i++) {
TreeNode* tmp = q.front();//取隊首
q.pop();//彈出隊首
sum += tmp->val;
if (tmp->left) q.push(tmp->left);//若存在,則左子入隊
if (tmp->right) q.push(tmp->right);//若存在,則右子入隊
}
result.push_back(sum/count);
}
return result;
}
};