【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
相关推荐
追随者永远是胜利者6 小时前
(LeetCode-Hot100)20. 有效的括号
java·算法·leetcode·职场和发展·go
清水白石0087 小时前
Python 纯函数编程:从理念到实战的完整指南
开发语言·python
twilight_4697 小时前
机器学习与模式识别——机器学习中的搜索算法
人工智能·python·机器学习
瓦特what?7 小时前
快 速 排 序
数据结构·算法·排序算法
niuniudengdeng7 小时前
基于时序上下文编码的端到端无文本依赖语音分词模型
人工智能·数学·算法·概率论
hetao17338377 小时前
2026-02-13~16 hetao1733837 的刷题记录
c++·算法
Jia ming8 小时前
《智能法官软件项目》—罪名初判模块
python·教学·案例·智能法官
Jia ming8 小时前
《智能法官软件项目》—法律文书生成模块
python·教学·案例·智能法官软件
曦月逸霜8 小时前
Python数据分析——个人笔记(持续更新中~)
python
海棠AI实验室8 小时前
第六章 从“能用”到“能交付”的关键一刀:偏好对齐(Preference Alignment)数据工程
python·私有模型训练