首页 > 代码库 > 637. 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. # 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



来自为知笔记(Wiz)


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