【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
相关推荐
naruto_lnq4 分钟前
Python日志记录(Logging)最佳实践
jvm·数据库·python
yuankoudaodaokou5 分钟前
高帧率扫描如何重塑动态三维扫描与思看科技300fps解决方案
python·科技
rainbow68896 分钟前
Python零基础到精通全攻略
python
酉鬼女又兒7 分钟前
SQL23 统计每个学校各难度的用户平均刷题数
数据库·sql·算法
毕设源码-朱学姐7 分钟前
【开题答辩全过程】以 基于python网络安全知识在线答题系统为例,包含答辩的问题和答案
开发语言·python·web安全
2301_765703148 分钟前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
爱学习的阿磊12 分钟前
模板代码跨编译器兼容
开发语言·c++·算法
Dxy123931021613 分钟前
Python判断MySQL表是否存在,不存在则创建
python·mysql·adb
毕设源码-钟学长15 分钟前
【开题答辩全过程】以 基于协同过滤推荐算法的小说漫画网站设计与实现为例,包含答辩的问题和答案
算法·机器学习·推荐算法
u01092727118 分钟前
代码覆盖率工具实战
开发语言·c++·算法