【LeetCode】每日一题:二叉树的层次遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

解题思路

水题

AC代码

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
class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        
        queue = [root]
        res = []

        while queue:
            length = len(queue)
            temp_res = []
            for _ in range(length):
                temp = queue[0]
                if temp.left: queue.append(temp.left)
                if temp.right: queue.append(temp.right)
                queue.remove(temp)
                temp_res.append(temp.val)
            res.append(temp_res)
        return res
相关推荐
2401_874732532 分钟前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
l1t9 分钟前
与系统库同名python脚本文件引起的奇怪错误及其解决
开发语言·数据库·python
Jackey_Song_Odd14 分钟前
Part 1:Python语言核心 - 内建数据类型
开发语言·python
小范自学编程21 分钟前
算法训练营 Day37 - 动态规划part06
算法·动态规划
带娃的IT创业者23 分钟前
WeClaw WebSocket 连接中断诊断:从频繁掉线到稳定长连的优化之路
python·websocket·网络协议·php·fastapi·实时通信
GinoWi23 分钟前
Chapter 4 Python中的循环语句和条件语句
python
GinoWi26 分钟前
Chapter 5 Python中的元组
python
星空露珠26 分钟前
迷你世界UGC3.0脚本Wiki角色模块管理接口 Actor
开发语言·数据库·算法·游戏·lua
我星期八休息27 分钟前
深入理解哈希表
开发语言·数据结构·c++·算法·哈希算法·散列表
一叶落43834 分钟前
LeetCode 54. 螺旋矩阵(C语言详解)——模拟 + 四边界收缩
java·c语言·数据结构·算法·leetcode·矩阵