【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
相关推荐
疋瓞30 分钟前
C++_STL和数据结构《1》_STL、STL_迭代器、c++中的模版、STL_vecto、列表初始化、三个算法、链表
数据结构·c++·算法
JJJJ_iii32 分钟前
【左程云算法09】栈的入门题目-最小栈
java·开发语言·数据结构·算法·时间复杂度
三体世界41 分钟前
测试用例全解析:从入门到精通(1)
linux·c语言·c++·python·功能测试·测试用例·测试覆盖率
Python私教44 分钟前
Django全栈班v1.04 Python基础语法 20250912 下午
后端·python·django
Bear on Toilet1 小时前
继承类模板:函数未在模板定义上下文中声明,只能通过实例化上下文中参数相关的查找找到
开发语言·javascript·c++·算法·继承
xchenhao1 小时前
Scikit-Learn 对糖尿病数据集(回归任务)进行全面分析
python·机器学习·回归·数据集·scikit-learn·特征·svm
金融小师妹1 小时前
多因子AI回归揭示通胀-就业背离,黄金价格稳态区间的时序建模
大数据·人工智能·算法
xchenhao1 小时前
Scikit-learn 对加州房价数据集(回归任务)进行全面分析
python·决策树·机器学习·回归·数据集·scikit-learn·knn
这里有鱼汤1 小时前
发现一个高性能回测框架,Python + Rust,比 backtrader 快 250 倍?小团队必备!
后端·python
☼←安于亥时→❦1 小时前
数据分析之Pandas入门小结
python·pandas