【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
相关推荐
前端梭哈攻城狮30 分钟前
dify二开示例
前端·后端·python
秋难降34 分钟前
一篇文章带你了解Pandassssssssssssssss
大数据·python·pandas
java1234_小锋36 分钟前
[免费]【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts)【论文+源码+SQL脚本】
python·flask·nlp·舆情分析·微博舆情分析
weixin_贾41 分钟前
模块自由拼装!Python重构DSSAT作物模块教程(以杂交水稻为例)
python·dssat
Warren981 小时前
Java Collections工具类
java·开发语言·笔记·python·学习·oracle·硬件工程
love530love2 小时前
Windows 11 下 Anaconda 命令修复指南及常见问题解决
运维·ide·人工智能·windows·python·架构·conda
NeoFii2 小时前
Day 24:元组与os模块
python·机器学习
半新半旧2 小时前
1.DRF 环境安装与配置
python·django
Sean_summer2 小时前
暑期第二周
前端·数据库·python
封奚泽优2 小时前
使用Python绘制金融数据可视化工具
python·信息可视化·excel·pandas·pyplot·qtwidgets·qtcore