当前位置:网站首页>[牛客网刷题 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
边栏推荐
- Typical low code apaas manufacturer cases
- UE pixel stream, come to a "diet pill"!
- [matlab] matlab reads and writes Excel
- Guess riddles (4)
- EA introduction notes
- Infected Tree(树形dp)
- Tips 1: Web video playback code
- go依赖注入--google开源库wire
- Keil use details -- magic wand
- STM32 --- GPIO configuration & GPIO related library functions
猜你喜欢

实例008:九九乘法表
![[three tier architecture]](/img/73/c4c75a453f03830e83cabb0762eb9b.png)
[three tier architecture]

Low code platform | apaas platform construction analysis

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

Bluebridge cup internet of things competition basic graphic tutorial - clock selection

STM32 single chip microcomputer - bit band operation

Example 002: the bonus paid by the "individual income tax calculation" enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increase

Arduino burning program and Arduino burning bootloader

Guess riddles (9)

One question per day - replace spaces
随机推荐
剑指 Offer 05. 替换空格
319. Bulb switch
Apaas platform of TOP10 abroad
GEO数据库中搜索数据
如何写Cover Letter?
STM32 --- serial port communication
Go dependency injection -- Google open source library wire
Arduino+a4988 control stepper motor
C language data type replacement
STM32---IIC
Explore the authentication mechanism of StarUML
[three tier architecture]
Stm32--- systick timer
Guess riddles (7)
Agile project management of project management
实例009:暂停一秒输出
Five design details of linear regulator
99 multiplication table (C language)
Example 001: the number combination has four numbers: 1, 2, 3, 4. How many three digits can be formed that are different from each other and have no duplicate numbers? How many are each?
go依赖注入--google开源库wire