【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
相关推荐
Wect11 小时前
LeetCode 39. 组合总和:DFS回溯解法详解
前端·算法·typescript
Wect11 小时前
LeetCode 46. 全排列:深度解析+代码拆解
前端·算法·typescript
颜酱11 小时前
Dijkstra 算法:从 BFS 到带权最短路径
javascript·后端·算法
木心月转码ing14 小时前
Hot100-Day24-T128最长连续序列
算法
小肥柴14 小时前
A2UI:面向 Agent 的声明式 UI 协议(三):相关概念和技术架构
算法
会员源码网14 小时前
Python中生成器函数与普通函数的区别
python
Java水解14 小时前
Python开发从入门到精通:Web框架Django实战
后端·python
曲幽16 小时前
FastAPI + PostgreSQL 实战:给应用装上“缓存”和“日志”翅膀
redis·python·elasticsearch·postgresql·logging·fastapi·web·es·fastapi-cache
学高数就犯困16 小时前
性能优化:LRU缓存(清晰易懂带图解)
算法
xlp666hub19 小时前
Leetcode第七题:用C++解决接雨水问题
c++·leetcode