LeetCode刷题笔记--637. Average of Levels in Binary Tree

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:

  1. 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了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值