zoukankan      html  css  js  c++  java
  • 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.

    以数组的形式返回每个层次上的节点的平均值

    C++(19ms):  bfs

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<double> averageOfLevels(TreeNode* root) {
    13         if (root == NULL)
    14             return vector<double>() ;
    15         vector<double> res ;
    16         queue<TreeNode*> que ;
    17         que.push(root) ;
    18         while(!que.empty()){
    19             long long sum = 0 ;
    20             int len = que.size() ;
    21             for(int i = 0 ; i < len ; i++){
    22                 TreeNode* t = que.front() ;
    23                 que.pop() ;
    24                 sum += t->val ;
    25                 if (t->left != NULL)
    26                     que.push(t->left) ;
    27                 if (t->right != NULL)
    28                     que.push(t->right) ;
    29             }
    30             res.push_back(sum/(len*1.0));
    31         }
    32         return res ;
    33     }
    34 };
  • 相关阅读:
    4.8日学习
    Apache安装
    HTML5 review
    个人阅读作业LAST
    个人阅读作业Week7
    结对编程:界面模块总结
    个人博客作业Week3
    结对编程博客
    个人博客week2
    软工第一次作业简单总结
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8005976.html
Copyright © 2011-2022 走看看