【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 小时前
leetcode hot100 64. 最小路径和 medium 递归优化
leetcode·深度优先
hrhcode2 小时前
【LangGraph】四.持久化:保存和恢复执行状态
python·ai·langchain·agent·langgraph
BirdenT2 小时前
20260424紫题训练
c++·算法
还是阿落呀2 小时前
基本控制结构
开发语言·c++·算法
xxyy8883 小时前
关于labelimg安装后在标注过程中闪退和死机的问题处理
开发语言·python
禧西3 小时前
面试准备——agent和大模型
面试·职场和发展
样例过了就是过了3 小时前
LeetCode热题100 最长有效括号
c++·算法·leetcode·动态规划
wayz113 小时前
Day 18:Keras深度学习框架入门
人工智能·深度学习·神经网络·算法·机器学习·keras
一行代码一行诗++3 小时前
C语言中if的使用
c语言·c++·算法
AI科技星3 小时前
《基于 1 的 N 维分形与对称统一理论》
人工智能·算法·机器学习·数学建模·数据挖掘