二叉树的层次遍历- python-队列

题目:

思路:

层次遍历要求从左到右访问节点,符合先进先出的顺序,所以要用到队列,在python中一般用deque双向队列

  1. 判断root是否为空,若为空,返回空列表
  2. 把root加入到队列中
  3. 当队列不为空
    1. for _ in range(len(queue)):
      1. 过渡列表temp=[]
      2. 取出队列的头部节点,并加入到temp中
      3. 判断该节点的左右子节点是否为空,不为空加入到队列中
    2. 一层的元素全部存在temp中,把temp加入到最终答案ans中
  4. 输出ans

代码:

复制代码
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        res, queue = [], deque()
        queue.append(root)
        while queue:
            temp = []
            for _ in range(len(queue)):
                node = queue.popleft()
                temp.append(node.val)
                if node.left:queue.append(node.left)
                if node.right:queue.append(node.right)
            res.append(temp)
        return res
相关推荐
monster000w4 小时前
大模型微调过程
人工智能·深度学习·算法·计算机视觉·信息与通信
小小晓.4 小时前
Pinely Round 4 (Div. 1 + Div. 2)
c++·算法
SHOJYS4 小时前
学习离线处理 [CSP-J 2022 山东] 部署
数据结构·c++·学习·算法
biter down4 小时前
c++:两种建堆方式的时间复杂度深度解析
算法
zhishidi4 小时前
推荐算法优缺点及通俗解读
算法·机器学习·推荐算法
WineMonk4 小时前
WPF 力导引算法实现图布局
算法·wpf
2401_837088505 小时前
双端队列(Deque)
算法
ada7_5 小时前
LeetCode(python)108.将有序数组转换为二叉搜索树
数据结构·python·算法·leetcode
奥特曼_ it5 小时前
【机器学习】python旅游数据分析可视化协同过滤算法推荐系统(完整系统源码+数据库+开发笔记+详细部署教程)✅
python·算法·机器学习·数据分析·django·毕业设计·旅游
仰泳的熊猫5 小时前
1084 Broken Keyboard
数据结构·c++·算法·pat考试