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

2023-12-22 06:24:33

此题看题解

题目链接

# 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

文章来源:https://blog.csdn.net/m0_53678795/article/details/135117299
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。