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.
Solution 1(C++)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
static int x=[](){std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }();
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> ans;
queue<TreeNode* > q;
q.push(root);
while(!q.empty()){
long sum = 0;
int len=q.size();
for(int i=0; i<len; i++){
TreeNode* temp=q.front();
q.pop();
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
sum += temp->val;
}
ans.push_back((double) sum/len);
}
return ans;
}
};
算法分析
这道题,很经典,从侧面反应了如何按层遍历一个树。那就是利用队列先进先出的特点。建立一个队列,然后将当前节点压入队列中,然后当队列不为空的时候,执行算法,如果队列都为空,说明所有压入队列的节点都为空,这代表树遍历完成,算法首先记录队列当前长度,这代表这一层有多少个节点,然后按照当前队列长度循环,取出首节点,记录并出队列。判断其两个子节点是否为空,分别压入栈。这个循环完成一次,队列中就是新的所有子节点。此时这边是下一层的根节点了。
然后在循环过程中记录节点的值,除以当前层的个数,也就是队列长度,即可。
程序分析
经典问题,多多复习。