当前位置:网站首页>[牛客网刷题 Day4] JZ32 从上往下打印二叉树
[牛客网刷题 Day4] JZ32 从上往下打印二叉树
2022-07-05 08:39:00 【strawberry47】
题目
不分行从上往下打印出二叉树的每个节点,同层节点从左至右打印。例如输入{8,6,10,#,#,2,1},如以下图中的示例二叉树,则依次打印8,6,10,2,1(空节点不打印,跳过),请你将打印的结果存放到一个数组里面,返回。
思路
可以用队列的思路:
from queue import Queue
class Solution:
def PrintFromTopToBottom(self , root: TreeNode):
# write code here
res = []
if root is None:
print("")
q = Queue()
q.put(root)
while not q.empty():
for i in range(q.qsize()):
node = q.get()
res.append(node.val)
if node.left:
q.put(node.left)
if node.right:
q.put(node.right)
return res
答案
答案里有递归的思路,还是搞不太明白是咋回事呢
import queue
class Solution:
def traverse(self, root: TreeNode, res: List[List[int]], depth: int):
if root:
# 新的一层
if len(res) < depth:
row = []
res.append(row)
row.append(root.val)
# 读取该层的一维数组,将元素加入末尾
else:
row = res[depth -1]
row.append(root.val)
else:
return
# 递归左右时深度记得加1
self.traverse(root.left, res, depth + 1)
self.traverse(root.right, res, depth + 1)
def PrintFromTopToBottom(self , root: TreeNode) -> List[int]:
res = []
temp = []
if not root:
return res
self.traverse(root, temp, 1)
#加入一维数组
for i in temp:
for j in i:
res.append(j)
return res
边栏推荐
- PIP installation
- 【日常训练--腾讯精选50】557. 反转字符串中的单词 III
- MATLAB skills (28) Fuzzy Comprehensive Evaluation
- Digital analog 2: integer programming
- STM32 single chip microcomputer - external interrupt
- Business modeling of software model | vision
- TypeScript手把手教程,简单易懂
- Example 009: pause output for one second
- 猜谜语啦(6)
- Arduino operation stm32
猜你喜欢

实例004:这天第几天 输入某年某月某日,判断这一天是这一年的第几天?

Digital analog 1: linear programming

Arduino operation stm32

Sword finger offer 09 Implementing queues with two stacks

Run menu analysis

Various types of questions judged by prime numbers within 100 (C language)

【NOI模拟赛】汁树(树形DP)

How apaas is applied in different organizational structures

STM32 --- serial port communication

Shell script
随机推荐
STM32 lights up the 1.8-inch screen under Arduino IDE
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
Digital analog 1: linear programming
L298N module use
实例006:斐波那契数列
Example 009: pause output for one second
Five design details of linear regulator
287. Looking for repeats - fast and slow pointer
【三层架构】
Guess riddles (8)
Apaas platform of TOP10 abroad
U8g2 drawing
Meizu Bluetooth remote control temperature and humidity access homeassistant
Example 007: copy data from one list to another list.
Business modeling of software model | overview
MATLAB skills (28) Fuzzy Comprehensive Evaluation
STM32 single chip microcomputer - bit band operation
[NAS1](2021CVPR)AttentiveNAS: Improving Neural Architecture Search via Attentive Sampling (未完)
Guess riddles (6)
如何写Cover Letter?