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

Posted Long Long Journey

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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





以上是关于637. Average of Levels in Binary Tree 二叉树每一层的平均值的主要内容,如果未能解决你的问题,请参考以下文章

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

637. Average of Levels in Binary Tree

LeetCode - 637. Average of Levels in Binary Tree

[leetcode-637-Average of Levels in Binary Tree]