【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
相关推荐
写代码写到手抽筋3 小时前
5G上行DCI字段判定:端口 流数 PMI选择详解
java·算法·5g
曲幽3 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
xieliyu.3 小时前
Java算法精讲:双指针(二)
java·开发语言·算法
装不满的克莱因瓶3 小时前
掌握 RNN 与 LSTM 模型结构
人工智能·python·rnn·深度学习·神经网络·ai·lstm
何以解忧,唯有..3 小时前
Python包管理工具pip:从入门到精通
开发语言·python·pip
wayz113 小时前
Momentum:PSL(心理线指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
金銀銅鐵4 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf4 小时前
Python 模块与包的导入导出
前端·后端·python
8Qi84 小时前
LeetCode 213:打家劫舍 II(House Robber II)—— 题解 ✅
算法·leetcode·职场和发展·动态规划
ice8130331814 小时前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib