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

637. Average of Levels in Binary Tree 二叉树每一层的平均值

时间:2017-07-09 19:46:58      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:pen   out   float   return   class   binary   normal   each   type   

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. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def averageOfLevels(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: List[float]
  12. """
  13. if(not root):
  14. return 0
  15. result = []
  16. queue = [root]
  17. while(queue):
  18. count = len(queue)
  19. sum = 0
  20. for i in range(0, count):
  21. node = queue.pop(0)
  22. sum += node.val
  23. if(node.left):
  24. queue.append(node.left)
  25. if(node.right):
  26. queue.append(node.right)
  27. result.append(sum * 1.0 / count)
  28. return result





637. Average of Levels in Binary Tree 二叉树每一层的平均值

标签:pen   out   float   return   class   binary   normal   each   type   

原文地址:http://www.cnblogs.com/xiejunzhao/p/7142333.html

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