【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
相关推荐
INGNIGHT8 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划
suhan8 小时前
【数据结构】七、查找:1.查找的概念、线性结构查找(顺序、折半(二分)、插值、稠密、分块、倒排)
数据结构·算法·排序算法
问心无愧05138 小时前
[护网杯 2018]easy_tornado
python·tornado
全栈弄潮儿8 小时前
Python实战第13期:模块与包
后端·python·编程语言
killerbasd9 小时前
总结 10.26
算法
深圳安锐科技有限公司9 小时前
从成像尺度到亚像素解算:变焦视觉位移监测如何让远近断面都稳
图像处理·人工智能·深度学习·算法·计算机视觉·系统架构·结构健康监测
2401_885885049 小时前
芬兰语音通知接口怎样对接?语音提醒接入流程
android·前端·python·php·语音识别
Dev _9 小时前
Python解释器安装在系统级目录导致命令行用户‌没有权限‌向该目录写入文件
开发语言·python
一只旭宝9 小时前
回调函数(Callback)
linux·服务器·算法
秋名RG9 小时前
算法的划分
算法