637. 二叉树的层平均值

每日一题20201124*(637. 二叉树的层平均值)

思路

继续采用广度优先遍历的方式,只需要稍微调整一下代码即可。可以参考: 

每日一题20201204(102. 二叉树的层序遍历)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def averageOfLevels(self, root: TreeNode) -> List[float]:
        if root is None:
            return []
        ans = []
        queue = [root]
        while len(queue) > 0:
            size = len(queue)
            # 记录这一层的总数
            total = 0
            for _ in range(size):
                current = queue.pop(0)
                total += current.val
                if current.left is not None:
                    queue.append(current.left)
                if current.right is not None:
                    queue.append(current.right)
            # ans数组添加进去平均值,不用担心size为0的问题,因为size肯定>0 
            # 因为queue后面的出队和入队已经不影响size了
            ans.append(total / size)
        return ans

每日一题20201124*(637. 二叉树的层平均值)

相关文章:

  • 2022-02-06
  • 2022-12-23
  • 2021-08-12
  • 2021-04-09
  • 2022-12-23
  • 2022-12-23
  • 2021-11-18
猜你喜欢
  • 2021-11-17
  • 2022-12-23
  • 2021-09-19
  • 2021-11-08
  • 2021-04-27
  • 2021-05-24
  • 2022-12-23
相关资源
相似解决方案