【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
相关推荐
DanCheng-studio7 分钟前
网安毕业设计课题思路
python·毕业设计·毕设
Code_流苏14 分钟前
Python星球日记 - 第20天:数据分析入门
python·数据分析·数据可视化·数据清洗·pandas库
毕小宝26 分钟前
Python 使用 copy_from 完成批量插入postgre数据库脚本分享
python
aaaweiaaaaaa27 分钟前
蓝桥杯c ++笔记(含算法 贪心+动态规划+dp+进制转化+便利等)
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
Hesse30 分钟前
希尔排序:Python语言实现
python·算法
love530love36 分钟前
PyCharm Community社区版链接WSL虚拟环境
ide·python·pycharm
船长@Quant37 分钟前
VectorBT量化入门系列:第一章 VectorBT基础与环境搭建
python·量化策略·sklearn·ta-lib·量化回测·vectorbt
XYN611 小时前
【嵌入式面试】
笔记·python·单片机·嵌入式硬件·学习
h^hh1 小时前
pipe匿名管道实操(Linux)
数据结构·c++·算法
dr李四维1 小时前
解决缓存穿透的布隆过滤器与布谷鸟过滤器:谁更适合你的应用场景?
redis·算法·缓存·哈希算法·缓存穿透·布隆过滤器·布谷鸟过滤器