【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
相关推荐
程序员大雄学编程10 分钟前
微积分43. 无穷积分入门:从概念到Python实战可视化
开发语言·python·学习·微积分
天疆说14 分钟前
庞特里亚金极小值原理的详细推导
算法
测试老哥16 分钟前
Postman获取token并设置token依赖步骤
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
郝学胜-神的一滴19 分钟前
C++11 工程级应用 06:自己造一个类似Python的Range迭代器
开发语言·c++·windows·python·程序人生·microsoft
满怀冰雪21 分钟前
23-PaddleClas 数据集、配置文件与训练参数详解
人工智能·python·深度学习·paddlepaddle
余俊晖27 分钟前
Self-OPD:去掉教师机的流匹配模型 On-Policy 蒸馏
人工智能·算法·机器学习
手写码匠28 分钟前
华为云Flexus+DeepSeek征文|华为云MaaS DeepSeek推理服务 × Flexus云服务器 × Dify一键部署:性能评测实战
人工智能·深度学习·算法·aigc
笔触狂放1 小时前
第3章 抓取静态网页数据
爬虫·python
海兰1 小时前
【 Python 量化交易】开篇
开发语言·python·信息可视化·量化交易
pt10431 小时前
网络自动化Python课程:Netconf与Restconf及Cisco自动化配置实验
网络·python·自动化