【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
相关推荐
mit6.8245 小时前
Xai架构
算法
WBluuue5 小时前
Codeforces 1078 Div2(ABCDEF1)
c++·算法
geovindu5 小时前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
寻星探路5 小时前
【JVM 终极通关指南】万字长文从底层到实战全维度深度拆解 Java 虚拟机
java·开发语言·jvm·人工智能·python·算法·ai
lbb 小魔仙5 小时前
【Java】Java 实战项目:手把手教你写一个电商订单系统
android·java·python
岱宗夫up5 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
Dxy12393102166 小时前
中文乱码恢复方案
开发语言·python
田里的水稻6 小时前
FA_融合和滤波(FF)-联邦滤波(FKF)
人工智能·算法·数学建模·机器人·自动驾驶
紫陌涵光6 小时前
112. 路径总和
java·前端·算法
回敲代码的猴子6 小时前
2月8日上机
开发语言·c++·算法