python3 佇列的使用

靖意风發表於2024-10-03

在leetcode 如下題目中使用佇列

637. 二叉樹的層平均值:

# 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]:
        ans = []
        queue = deque([root])

        while queue:
            sum = 0
            cnt = len(queue)
            for i in range(cnt):
                node = queue.popleft()
                sum += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

            ans.append(sum/cnt)

        return ans

相關文章