【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
相关推荐
简单点好不好14 小时前
工作中的工程问题: 找圆?
算法
阿Y加油吧14 小时前
两道字符串 DP 模板题复盘:最长公共子序列 & 编辑距离
leetcode
我爱cope15 小时前
【力扣hot100:76. 最小覆盖子串】
算法·leetcode·职场和发展
社交怪人15 小时前
【歌手大奖赛】信息学奥赛一本通C语言解法(题号2072)
c语言·算法
晚霞的不甘15 小时前
CANN Catlass 矩阵乘模板库深度解析:高性能矩阵运算的进阶之路
人工智能·python·线性代数·矩阵
数据科学小丫15 小时前
算法:逻辑回归
算法·机器学习·逻辑回归
爱写代码的小朋友15 小时前
基于多约束遗传算法的中小学排座位优化模型研究
linux·人工智能·算法
один but you15 小时前
unorder_map 和unorder_set
算法·哈希算法·散列表
sheeta199815 小时前
LeetCode 每日一题笔记 日期:2026.05.20 题目:2657. 找到前缀公共数组
笔记·算法·leetcode
小白学大数据15 小时前
深度探索:Python 爬虫实现豆瓣音乐全站采集
开发语言·爬虫·python·数据分析