当前位置:网站首页>[牛客网刷题 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
边栏推荐
- 实例005:三数排序 输入三个整数x,y,z,请把这三个数由小到大输出。
- Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
- C language data type replacement
- Digital analog 1: linear programming
- Run菜单解析
- STM32 --- GPIO configuration & GPIO related library functions
- 【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
- 【日常训练--腾讯精选50】557. 反转字符串中的单词 III
- Five design details of linear regulator
- Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off
猜你喜欢

Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off

99 multiplication table (C language)

Arduino+a4988 control stepper motor

Arduino burning program and Arduino burning bootloader

猜谜语啦(2)

剑指 Offer 06. 从尾到头打印链表

Explore the authentication mechanism of StarUML

How to manage the performance of R & D team?

MATLAB skills (28) Fuzzy Comprehensive Evaluation

UE像素流,来颗“减肥药”吧!
随机推荐
Digital analog 1: linear programming
Detailed summary of FIO test hard disk performance parameters and examples (with source code)
STM32 single chip microcomputer - external interrupt
319. Bulb switch
696. Count binary substring
Lori remote control commissioning record
MySQL MHA high availability cluster
MySQL之MHA高可用集群
Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?
Weidongshan Internet of things learning lesson 1
实例009:暂停一秒输出
go依赖注入--google开源库wire
leetcode - 445. Add two numbers II
剑指 Offer 09. 用两个栈实现队列
Lori remote control LEGO motor
UE像素流,来颗“减肥药”吧!
Guess riddles (142)
Business modeling | process of software model
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
暑假第一周