【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
相关推荐
高洁0117 小时前
DNN案例一步步构建深层神经网络(二)
人工智能·python·深度学习·算法·机器学习
Insight.17 小时前
背包问题——01背包、完全背包、多重背包、分组背包(Python)
开发语言·python
aini_lovee17 小时前
改进遗传算法求解VRP问题时的局部搜索能力
开发语言·算法·matlab
Lucky高17 小时前
Pandas库实践1_预备知识准备
python·pandas
老蒋新思维18 小时前
反脆弱性设计:创始人IP与AI智能体如何构建愈动荡愈强大的知识商业|创客匠人
人工智能·网络协议·tcp/ip·算法·机器学习·创始人ip·创客匠人
Salt_072818 小时前
DAY 36 官方文档的阅读
python·算法·机器学习·github
k***921618 小时前
Python 科学计算有哪些提高运算速度的技巧
开发语言·python
superman超哥18 小时前
仓颉条件变量深度解析与实践:解锁高效并发同步
开发语言·python·c#·仓颉
长空任鸟飞_阿康18 小时前
LangGraph 技术详解:基于图结构的 AI 工作流与多智能体编排框架
人工智能·python·langchain
love530love19 小时前
ComfyUI 升级 v0.4.0 踩坑记录:解决 TypeError: QM_Queue.task_done() 报错
人工智能·windows·python·comfyui