【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
相关推荐
DogDaoDao15 小时前
【第 05 篇】Python的字典与集合
开发语言·python·集合·字典
兰令水15 小时前
leecodecode【单调栈】【2026.6.12打卡-java版本】
java·开发语言·算法
涛声依旧-底层原理研究所15 小时前
混合检索 + 重排:让 AI Agent 拥有「既全又准」的认知骨架
人工智能·python
努力写A题的小菜鸡15 小时前
01-PyTorch加载数据初认识(dataset运用)
人工智能·pytorch·python
abcy07121315 小时前
python fastapi celery hdfs 异步上传
python·hdfs·fastapi
TMT星球15 小时前
魔法原子上交会首秀VLA K02大模型,完成具身智能从“执行”到“理解”的能力跃迁
人工智能·算法·机器学习
Dxy123931021615 小时前
Python多线程如何操作全局变量:从踩坑到最佳实践
python
2301_7644413315 小时前
番茄钟+AI:高效专注的秘密武器
人工智能·算法·数学建模·动态规划·交互
影寂ldy15 小时前
C# 泛型委托
java·算法·c#
SilentSamsara15 小时前
RAG 系统入门:LangChain/LlamaIndex + Chroma 向量数据库的检索增强实战
数据库·人工智能·python·青少年编程·langchain