【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
相关推荐
2301_7944615711 分钟前
力扣-283-移动零
算法·leetcode·职场和发展
编程绿豆侠12 分钟前
力扣HOT100之二叉树:98. 验证二叉搜索树
算法·leetcode·职场和发展
正在走向自律14 分钟前
Conda 完全指南:从环境管理到工具集成
开发语言·python·conda·numpy·fastapi·pip·开发工具
技术流浪者28 分钟前
C/C++实践(十)C语言冒泡排序深度解析:发展历史、技术方法与应用场景
c语言·数据结构·c++·算法·排序算法
lqjun082735 分钟前
PyTorch实现CrossEntropyLoss示例
人工智能·pytorch·python
DpHard1 小时前
Vscode 配置python调试环境
ide·vscode·python
小蜗笔记1 小时前
显卡、Cuda和pytorch兼容问题
人工智能·pytorch·python
I AM_SUN1 小时前
98. 验证二叉搜索树
数据结构·c++·算法·leetcode
高建伟-joe1 小时前
内容安全:使用开源框架Caffe实现上传图片进行敏感内容识别
人工智能·python·深度学习·flask·开源·html5·caffe
学习中的码虫1 小时前
数据结构基础排序算法
数据结构·算法·排序算法