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.
The key is how to determine which nodes are in the same layer. Queue solution: from the root down, fill a layer of nodes into the queue every time, the first time is the root, then calculate the queue size at this time, which is the number of nodes in the first layer. For loop process all nodes in the first layer, put its left and right sub-nodes on the stack (if there is one), and accumulate the section. At the end of the loop, the average val ue of the first layer is calculated. At this time, all the nodes in the queue are in the second layer. By analogy, the number of nodes in the second layer is n2. Two head elements are popped up from the queue for processing, and then the third layer node is put at the end of the queue... Until the queue is empty.
/**
* 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;//Node queue
vector<double> result;
q.push(root);//From the root
while (!q.empty()) {
int count = q.size();//Record the size of this layer
double sum = 0.0;//Cumulative sum
for (int i = 0; i < count; i++) {
TreeNode* tmp = q.front();//Take the lead
q.pop();//Pop-up team leader
sum += tmp->val;
if (tmp->left) q.push(tmp->left);//If it exists, the left son will join the team.
if (tmp->right) q.push(tmp->right);//If it exists, the right son will join the team.
}
result.push_back(sum/count);
}
return result;
}
};