【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
相关推荐
毋语天2 分钟前
Python 常用内置模块详解:日志、随机数、时间、OS 与 JSON
开发语言·python
Asa121385 分钟前
Nature Microbiology|跨微生物界菌株水平传播推断的新算法TRACS
算法
右耳朵猫AI9 分钟前
Python技术周刊 2026年第14周
开发语言·python·okhttp
2501_9012005310 分钟前
MongoDB事务会产生多少性能损耗
jvm·数据库·python
zh15702317 分钟前
CSS如何通过Sass循环生成辅助类_批量创建颜色或间距样式
jvm·数据库·python
加号317 分钟前
【Python】 实现 HTTP 网络请求功能入门指南
网络·python·http
叼烟扛炮18 分钟前
C++ 知识点22 函数模板
开发语言·c++·算法·函数模版
神明93119 分钟前
golang如何实现滚动更新方案_golang滚动更新方案实现实战
jvm·数据库·python
CLX050519 分钟前
mysql复杂查询语句如何调优_通过改写子查询为JOIN连接
jvm·数据库·python
Tisfy21 分钟前
LeetCode 2553.分割数组中数字的数位:模拟(maybe+翻转)——java也O(1)
java·数学·算法·leetcode·题解·模拟·取模