【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
相关推荐
熬了夜的程序员1 小时前
【LeetCode】114. 二叉树展开为链表
leetcode·链表·深度优先
程序员爱钓鱼2 小时前
Python 综合项目实战:学生成绩管理系统(命令行版)
后端·python·ipython
Brsentibi2 小时前
基于python代码自动生成关于建筑安全检测的报告
python·microsoft
程序员爱钓鱼2 小时前
REST API 与前后端交互:让应用真正跑起来
后端·python·ipython
gCode Teacher 格码致知4 小时前
Python基础教学:Python的openpyxl和python-docx模块结合Excel和Word模板进行数据写入-由Deepseek产生
python·excel
大胆飞猪5 小时前
递归、剪枝、回溯算法---全排列、子集问题(力扣.46,78)
算法·leetcode·剪枝
Destiny_where6 小时前
Agent平台-RAGFlow(2)-源码安装
python·ai
molunnnn6 小时前
第四章 Agent的几种经典范式
开发语言·python
Kisorge7 小时前
【电机控制】基于STM32F103C8T6的二轮平衡车设计——LQR线性二次线控制器(算法篇)
stm32·嵌入式硬件·算法
linuxxx1108 小时前
django测试缓存命令的解读
python·缓存·django