【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
相关推荐
北顾笙9801 天前
day11-数据结构力扣
数据结构·算法·leetcode
蓝之静云1 天前
mapper执行sql报空指针,需要传入参数
数据库·python·sql
月落归舟1 天前
Lambda + Arrays---小练习
数据结构·算法
2601_955354461 天前
seo臻系统和百度seo有什么区别
算法
wggmrlee1 天前
Mac安装Anaconda
python·fastapi
YuanDaima20481 天前
解决Conda环境下RTX 50系列显卡PyTorch+Transformers+PEFT微调报错
人工智能·pytorch·笔记·python·深度学习·机器学习·conda
君义_noip1 天前
信息学奥赛一本通 1487:【例 2】北极通讯网络
算法·图论·信息学奥赛·csp-s
okiseethenwhat1 天前
反射在 JVM 层面的实现原理
开发语言·jvm·python
XiYang-DING1 天前
【Java SE】sealed关键字
java·开发语言·python
weixin_449290011 天前
Python vs Go:优缺点对比
网络·python·golang