Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

 

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.

 

1、用层序遍历BFS。并且每次把当前层的节点加到temp,遍历上一次队列之后,再用temp更新它。。

class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> re;
        if(!root)
            return re;
        queue<TreeNode*>TQueue;
        TQueue.push(root);
        while(!TQueue.empty())
        {
            double MySum=0;
            int index=0;
            queue<TreeNode*>TQtemp;
            while(!TQueue.empty())
            {
                TreeNode* temp=TQueue.front();
                TQueue.pop();
                MySum+=temp->val;
                index++;

                if(temp->left)
                {
                    TQtemp.push(temp->left);
                }
                if(temp->right)
                {
                    TQtemp.push(temp->right);
                }
                
            }
            re.push_back(MySum/index);
            TQueue=TQtemp; 
        }
        return re;
        
    }
};

 

 

 

2、DFS遍历,用i记录当前层序号,并用两个vector分别保存当前层的的节点之和和节点个数。

class Solution {
public:
    void MyAverage(TreeNode*root,int i,vector<double>&sum,vector<int>&count)
    {
        if(root==nullptr)
            return;
        if(i<sum.size())   //i表示当前层0就是root,sum.size()就是已经有的层数
        {
            //sum的层数已经有了
            sum[i]=sum[i]+root->val;
            count[i]++;
            
        }
        else
        {
            sum.push_back(root->val);
            count.push_back(1);
            
        }
        MyAverage(root->left,i+1,sum,count);
        MyAverage(root->right,i+1,sum,count);
        
    }
    
    
    vector<double> averageOfLevels(TreeNode* root) {
        vector<double> re;
        if(!root)
            return re;
       
        vector<int>count;
        MyAverage(root,0,re,count);
        for(int i=0;i<re.size();i++)
        {
            re[i]/=count[i];
            
        }
        return re;
        
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值