【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
相关推荐
_WndProc6 分钟前
【Python】Flask网页
开发语言·python·flask
互联网搬砖老肖8 分钟前
Python 中如何使用 Conda 管理版本和创建 Django 项目
python·django·conda
测试者家园19 分钟前
基于DeepSeek和crewAI构建测试用例脚本生成器
人工智能·python·测试用例·智能体·智能化测试·crewai
liujing1023292922 分钟前
Day04_刷题niuke20250703
java·开发语言·算法
大模型真好玩24 分钟前
准确率飙升!Graph RAG如何利用知识图谱提升RAG答案质量(四)——微软GraphRAG代码实战
人工智能·python·mcp
前端付豪31 分钟前
11、打造自己的 CLI 工具:从命令行到桌面效率神器
后端·python
前端付豪32 分钟前
12、用类写出更可控、更易扩展的爬虫框架🕷
后端·python
江太翁42 分钟前
Pytorch torch
人工智能·pytorch·python
2401_881244401 小时前
Treap树
数据结构·算法
乌萨奇也要立志学C++1 小时前
二叉树OJ题(单值树、相同树、找子树、构建和遍历)
数据结构·算法