https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/description/
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;
}
};