当前位置:网站首页>剑指 Offer 32 - II. 从上到下打印二叉树 II for_in range()
剑指 Offer 32 - II. 从上到下打印二叉树 II for_in range()
2022-07-16 03:22:00 【愈努力俞幸运】
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
广度优先搜索通常借助队列实现。
如何按层打印呢?
每层打印的节点的个数进入该层时,队列中元素的个数。
那这样就搞定了。
'''
for _ in range(5):
print("*")
# 其中’_’是一个循环标志,
# 也可以用i,j 等其他字母代替,
# 下面的循环中不会用到,起到的是循环此数的作用
'''
import collections
class Solution:
def levelOrder(self, root):
if not root:
return []
res,qu=[],collections.deque()
qu.append(root)
while qu:
tmp=[];
for _ in range(len(qu)):#'_'占位符
node=qu.popleft()
tmp.append(node.val)
if node.left:
qu.append(node.left)
if node.right:
qu.append(node.right)
res.append(tmp)
return res
边栏推荐
- Paper reading: u-net: revolutionary networks for biomedical image segmentation
- 【机器学习】自动编码器 - Autoencoder
- Talk about data overflow
- 工作方法记录
- 群晖7.1使用SHR添加硬盘
- 03_案例搭建【RestTemplate 调用微服务】
- 什么是ECS框架?讲解 + 实战带你入门ECS框架
- 端口轉發工具 rinetd
- Iptables port forwarding
- 论文阅读:U-Net: Convolutional Networks for Biomedical Image Segmentation
猜你喜欢

mysql触发器和存储过程

IIC读写EEPROM

社区峰会|Pulsar Summit 旧金山峰会议题亮点曝光!

Reduce debugging costs by 50%. Xiaojiang IOT pushes a remote serial port debugging assistant

Add right click to create a markdown file

Talk about data overflow

hcip静态综合复习实验

群晖7.1使用SHR添加硬盘
![[programming training 10] tic tac toe chess + password strength level](/img/b4/f266eaf89393d28a437c592f95e81d.png)
[programming training 10] tic tac toe chess + password strength level

剑指 Offer 63. 股票的最大利润
随机推荐
金仓数据库 KingbaseES SQL语言参考手册(2. KingbaseES SQL介绍)
ES6笔记二
Google Earth engine app (GEE) - load a searchable Spector
端口轉發工具 rinetd
Kingbasees SQL language reference manual of Jincang database (3.1.1.9. network address type)
【随记】从入门到入土的密码学 | 概述
Golang empty interface
[programming training 4] calculate candy + hexadecimal conversion
hcip第五天筆記
Runtimeerror: the size of tensor a (4) must match the size of tensor B (3) at non singleton
Kingbasees SQL language reference manual of Jincang database (3.1.1.4. date / time type)
hcip第五天笔记
【机器学习】随机森林 – Random forest
IO Language Guide
【RT-Thread】nxp rt10xx 设备驱动框架之--uart搭建和使用
简述memcached的工作原理
金仓数据库 KingbaseES SQL 语言参考手册 (3.1.1.13. JSON 类型)
【机器学习】PCA - 主成分分析
台式万用表究竟如何选型?
HCIP Day 5 Notes