637.二叉树的层平均值

2023.6.12
层序遍历加求平均值

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:        
        if not root:
            return []
        queue = collections.deque()
        queue.append(root)
        res = []
        while queue:
            level = 0
            size = len(queue)
            for i in range(size):
                node = queue.popleft()
                level += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(level/size)
        return res

你可能感兴趣的:(Notes,of,Leetcode,python,开发语言)