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.

    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






  • 相关阅读:
    HTML5新增的属性和废除的属性
    利用ajax的方式来提交数据到后台数据库及交互功能
    在BS表单上使用fastreport.net
    js获取电子秤串口数据
    XMPP基础
    xmpp简介
    扩展方法
    泛型委托、lambda表达式例子,备忘
    leetcode 127. Word Ladder ----- java
    leetcode 126. Word Ladder II ----- java
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7142333.html
Copyright © 2011-2022 走看看