【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
相关推荐
MIngYaaa5203 分钟前
2026暑期牛客多校3 2026-7-24
数据结构·算法·000
这个人懒得名字都没写15 分钟前
Flask + PyArmor Gunicorn启动报错:RuntimeError: unauthorised use of script
python·flask·gunicorn·pyarmor
C++、Java和Python的菜鸟21 分钟前
第10章 后端Web进阶(Maven高级)
开发语言·python
暗黑小白36 分钟前
路由策略与引擎可替换性
后端·python·ai agent
geats人山人海39 分钟前
算法基础第二讲 基础算法下
算法
小罗水1 小时前
第 20 章 高级 RAG 技术与检索优化
人工智能·python·机器学习
阳明山水1 小时前
销量预测2026下半年:新架构、新基准与新共识
人工智能·深度学习·算法·机器学习·架构
bamb001 小时前
一个项目带你入门AI应用开发06
python
知识分享小能手1 小时前
高等数学学习教程,从入门到精通,定积分 — 知识点全面总结(9)
学习·算法·机器学习
noipp1 小时前
推荐题目:洛谷 P3726 [AHOI2017/HNOI2017] 抛硬币
c语言·数据结构·c++·算法·编程·洛谷·luogu