二叉树的层次遍历- 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
相关推荐
信奥卷王5 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵5 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG6 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z7 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛7 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记7 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序8 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm
小O的算法实验室8 小时前
IEEE TMC,面向异构物联网的多目标量子行为拓扑优化算法
算法
liliangcsdn9 小时前
派息率指标的应用探索和分析
大数据·算法