637. Average of Levels in Binary Tree
Easy
762120FavoriteShare
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.
这道题和102,107类似,原理的话可以参考以下链接中的分析:
102题: https://blog.csdn.net/vivian0239/article/details/88555561
107题: https://blog.csdn.net/vivian0239/article/details/88556765
先上AC代码,然后说一下这道题和102,107比多出来的注意点在哪里:
/**
* 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> y;
y.clear();
if(!root)return y;
queue<TreeNode*> que;
que.push(root);
while(que.size())
{
int num=que.size();
int nx=num;
long x=0;
while(num>0)
{
TreeNode* t=que.front();
x+=t->val;
que.pop();
if(t->left)que.push(t->left);
if(t->right)que.push(t->right);
num--;
}
y.push_back((double)x/nx);
}
return y;
}
};
注意点1:testcase中有
[2147483647,2147483647,2147483647]
这个就是32位int最大值,如果x是int,那就会溢出,所以需要把x改为long,这样就能通过了。
注意点2:当心分母为0的情况。这一点我悲剧地放到vs里跑了才发现,真是不小心。一开始我是y.push_back((double)x/num), 这样就错了。因为在num--以后,最后进到这一句时,num必然为0。所以需要重新定义一个int xn=num,防止num最后变成0,最后这句改为:y.push_back((double)x/nx);。这样就OK了。