【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
相关推荐
小白菜又菜5 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
cnxy1886 小时前
围棋对弈Python程序开发完整指南:步骤1 - 棋盘基础框架搭建
开发语言·python
落叶,听雪6 小时前
河南建站系统哪个好
大数据·人工智能·python
wuhen_n6 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo6 小时前
leetcode 2483
数据结构·算法·leetcode
极客小云7 小时前
【生物医学NLP信息抽取:药物识别、基因识别与化学物质实体识别教程与应用】
python·机器学习·nlp
南_山无梅落7 小时前
12.Python3函数基础:定义、调用与参数传递规则
python
Xの哲學7 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢7 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
油泼辣子多加8 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习