【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
相关推荐
沈浩(种子思维作者)9 小时前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
MM_MS9 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
独自破碎E9 小时前
【二分法】寻找峰值
算法
njsgcs10 小时前
ue python二次开发启动教程+ 导入fbx到指定文件夹
开发语言·python·unreal engine·ue
io_T_T10 小时前
迭代器 iteration、iter 与 多线程 concurrent 交叉实践(详细)
python
mit6.82410 小时前
位运算|拆分贪心
算法
华研前沿标杆游学10 小时前
2026年走进洛阳格力工厂参观游学
python
Carl_奕然10 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析
ghie909010 小时前
基于MATLAB的TLBO算法优化实现与改进
开发语言·算法·matlab
恋爱绝缘体110 小时前
2020重学C++重构你的C++知识体系
java·开发语言·c++·算法·junit