【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
相关推荐
鱼跃鹰飞3 分钟前
面试题:说说MMAP和DMA/SG-DMA的关系
面试·职场和发展·架构·系统架构
huwei8534 分钟前
python设计通用表格类 带右键菜单
开发语言·windows·python
计算机毕业编程指导师4 分钟前
【计算机毕设选题】基于Spark的拉勾网招聘数据分析系统源码,Python+Django全流程
大数据·hadoop·python·spark·django·招聘·拉勾网
duyinbi75178 分钟前
TOOD_R50_FPN_Anchor-Based_1x_COCO_列车悬挂部件检测分类实战
python
进击的横打8 分钟前
【车载开发系列】安全算法与安全访问
算法·安全·车载系统
努力学算法的蒟蒻9 分钟前
day59(1.18)——leetcode面试经典150
算法·leetcode·职场和发展
学习3人组10 分钟前
大模型轻量化调优(昇腾平台方向)岗位技术名词拆解
人工智能·python
666HZ66611 分钟前
数据结构3.0 栈、队列和数组
开发语言·数据结构·算法
知乎的哥廷根数学学派12 分钟前
基于物理引导和不确定性量化的轻量化神经网络机械退化预测算法(Python)
人工智能·pytorch·python·深度学习·神经网络·算法·机器学习
程序员-King.13 分钟前
day146—递归—验证二叉搜索树(LeetCode-98)
算法·leetcode·二叉树·递归