当前位置: 首页 > news >正文

[LeetCode]102.二叉树的层序遍历(python)

1.代码

from collections import deque
from typing import List
# 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]]: i = 0queue = deque()result : List[List[int]] = []if root==None:return resultqueue.append(root)while(queue):length = len(queue)result.append([])for j in range (length):item = queue.popleft()if item.left:queue.append(item.left)if item.right:queue.append(item.right)result[i].append(item.val)i=i+1return result

2.思路

用一个队列控制遍历,一开始队列中只有root,每一次通过检查队列的长度,控制出队的元素个数恰好为一层的个数。每次一个元素出队,依次将它的左右子节点入队,并计入result中对应数组。


http://www.mrgr.cn/news/10495.html

相关文章:

  • Java-使用HashMap压缩重复数据量以减少堆内存溢出的概率
  • CSS3页面布局-三栏-中栏流动布局
  • ECMAScript 性能优化技巧与陷阱
  • 将 github 仓库同步到个人服务器
  • Redis(面试题【速记】)
  • 无人机+消防车:高楼灭火系统技术详解
  • 如何合理设置PostgreSQL的`max_connections`参数
  • linux swap slot机制
  • mysql练习5
  • 内网穿透的几种方法
  • PHP 全攻略:从环境搭建到实战项目的深度探索
  • 防患未然:构建AIGC时代下开发团队应对突发技术故障与危机的全面策略
  • Swagger的增强knife4j
  • 如何在 EcoVadis 平台上注册账号?
  • 如何使用ssm实现基于java的小型超市管理系统+vue
  • [windows][软件]Windows平台MongoDB的安装
  • 电脑日常笔记目录
  • 发现一个通用的滑块验证码缺口识别库 captcha-recognizer (两行代码识别滑块验证码缺口)
  • SQL,解析 json
  • 追问试面试系列:分布式事务