【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
相关推荐
孑渡14 分钟前
【LeetCode】每日一题:跳跃游戏 II
python·算法·leetcode·游戏·职场和发展
dandanforgetlove17 分钟前
python pdfplumber优化表格提取
开发语言·windows·python
ka2x19 分钟前
订单折扣金额分摊算法|代金券分摊|收银系统|积分分摊|分摊|精度问题|按比例分配|钱分摊|钱分配
java·c语言·c++·python·算法·spring·spring cloud
职略2 小时前
负载均衡类型和算法解析
java·运维·分布式·算法·负载均衡
A22742 小时前
LeetCode 196, 73, 105
java·算法·leetcode
阿里巴巴P8资深技术专家3 小时前
Java常用算法&集合扩容机制分析
java·数据结构·算法
zengson_g4 小时前
当需要对大量数据进行排序操作时,怎样优化内存使用和性能?
java·数据库·算法·排序算法
爱上电路设计4 小时前
有趣的算法
开发语言·c++·算法
2401_858120265 小时前
探索sklearn文本向量化:从词袋到深度学习的转变
开发语言·python·机器学习
bigbearxyz6 小时前
Java实现图片的垂直方向拼接
java·windows·python