637. Average of Levels in Binary Tree

来源:互联网 发布:百度程序员待遇 编辑:程序博客网 时间:2024/04/29 18:33

题目描述:

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   7Output: [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.
做题思路:

利用层次遍历,重点在于分层,分出层之后就能求出每一层的平均值了。时间复杂度O(n)

答案详解:

/**

 * 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> a;
        TreeNode* p = root;
        int rear = -1;//生命队列的前后位置
        int front = -1;
        int last = 0;//当front等于last时,level++
        int level = 0;
        struct TreeNode* q[10001];//将节点存在队列里面
        double ave;//每层的平均数
        int i = 0;//每一层有几个节点
        
        if(root=NULL){
            a.push_back(NULL);
            return a;
        }
        
        q[++rear] = p;//初始化第一个节点
        i=0;
        
        while(front<rear)
        {
            ave = ave + q[++front]->val;
            cout<< ave << endl;
            p = q[front];
            i++;
            if(p->left){
                q[++rear] = p->left;
            }
            if(p->right){
                q[++rear] = p->right;
            }
            if( front == last)
            {
                a.push_back(ave/i);
                last = rear;
                ave = 0;
                i=0;
            }
        }
        return a;
    }
};
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 ubuntu完全卡死怎么办 win10以太网没了怎么办 hks泄压阀声音小怎么办 声卡驱动删除了怎么办 白色水彩没有了怎么办 大学毕业我想考军校怎么办? 考军校分数不够怎么办 大专工作不好找怎么办 小学二年级插班怎么办 进厂年龄不到怎么办 入伍批准书丢了怎么办 考驾照期间参军怎么办 学位房被占用怎么办 教室里回音太大怎么办 教室里味道太大怎么办 键盘只能打拼音怎么办 一师一优课件上传慢怎么办? 药店买药不给退怎么办 小孩热感冒发烧怎么办 孕妇热感冒了怎么办 孕妇热感冒喉咙痛怎么办 空军一号有划痕怎么办 高铁上乘客太吵怎么办 军官礼服丢了怎么办 空军大檐帽帽袋坏了怎么办 保安不发工资怎么办 做保安工资不资不发怎么办 公安改革辅警怎么办 皮带带子丢了怎么办 警校学生证丢了怎么办 警校证丢了怎么办 盘查没带身份证怎么办 网线拔不出来怎么办 车间压强差过大怎么办 不遵守交通规则交警怎么办 西裤屁股磨出光该怎么办 中暑发烧不退烧怎么办 小孩中暑反复发烧怎么办 上火导致的发烧怎么办 夏季运动中暑后怎么办 感觉中暑了头疼怎么办