Leetcode-102.二叉树的层序遍历(Python)

此题看题解

题目链接

# 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
from collections import deque
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        res=[]
        queue=deque([root])
        while queue:
            level_size=len(queue)
            level_value=[]
            for i in range(level_size):
                node=queue.popleft()
                level_value.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            res.append(level_value)
        return res

你可能感兴趣的:(leetcode,leetcode,算法,python)