二叉树的层次遍历- 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
相关推荐
YGGP1 天前
【Golang】LeetCode 64. 最小路径和
算法·leetcode
古城小栈1 天前
Rust变量设计核心:默认不可变与mut显式可变的深层逻辑
算法·rust
电商API&Tina1 天前
跨境电商 API 对接指南:亚马逊 + 速卖通接口调用全流程
大数据·服务器·数据库·python·算法·json·图搜索算法
LYFlied1 天前
【每日算法】LeetCode 1143. 最长公共子序列
前端·算法·leetcode·职场和发展·动态规划
长安er1 天前
LeetCode 20/155/394/739/84/42/单调栈核心原理与经典题型全解析
数据结构·算法·leetcode·动态规划·
MarkHD1 天前
智能体在车联网中的应用:第28天 深度强化学习实战:从原理到实现——掌握近端策略优化(PPO)算法
算法
能源系统预测和优化研究1 天前
【原创代码改进】考虑共享储能接入的工业园区多类型负荷需求响应经济运行研究
大数据·算法
yoke菜籽1 天前
LeetCode——三指针
算法·leetcode·职场和发展
小高不明1 天前
前缀和一维/二维-复习篇
开发语言·算法
bin91531 天前
当AI优化搜索引擎算法:Go初级开发者的创意突围实战指南
人工智能·算法·搜索引擎·工具·ai工具