码迷,mamicode.com
首页 > 其他好文 > 详细

Average of Levels in Binary Tree

时间:2017-11-10 15:04:24      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:struct   tor   push   dfs   self   cto   pop   blog   pen   

C++:

/**
 * 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> res;
        queue<TreeNode*> q;
        q.push(root);
        double sum,avg;
        while(!q.empty())
        {
            int num=q.size();
            sum=0;
            for(int i=0;i<num;i++)
            {
                TreeNode* temp=q.front();
                sum+=temp->val;
                q.pop();
                if(temp->left!=NULL)
                    q.push(temp->left);
                if(temp->right!=NULL)
                    q.push(temp->right);
                
            }
            avg=sum/num;  
            res.push_back(avg);
        }
        return res;
    }
};  
def averageOfLevels(self, root):
    info = []
    def dfs(node, depth = 0):
        if node:
            if len(info) <= depth:
                info.append([0, 0])
            info[depth][0] += node.val
            info[depth][1] += 1
            dfs(node.left, depth + 1)
            dfs(node.right, depth + 1)
    dfs(root)

    return [s/float(c) for s, c in info]

  

Average of Levels in Binary Tree

标签:struct   tor   push   dfs   self   cto   pop   blog   pen   

原文地址:http://www.cnblogs.com/xlqtlhx/p/7814236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!