当前位置:网站首页>[牛客网刷题 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
边栏推荐
- MATLAB小技巧(28)模糊綜合評價
- Shell script
- Several problems to be considered and solved in the design of multi tenant architecture
- MATLAB小技巧(28)模糊综合评价
- Count the number of inputs (C language)
- An enterprise information integration system
- 剑指 Offer 05. 替换空格
- STM32 single chip microcomputer - bit band operation
- Run menu analysis
- Guess riddles (7)
猜你喜欢
猜谜语啦(2)
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
STM32 lights up the 1.8-inch screen under Arduino IDE
Example 007: copy data from one list to another list.
Arduino burning program and Arduino burning bootloader
Low code platform | apaas platform construction analysis
Detailed summary of FIO test hard disk performance parameters and examples (with source code)
Run菜单解析
Business modeling | process of software model
Typical low code apaas manufacturer cases
随机推荐
PIP installation
[formation quotidienne - Tencent Selection 50] 557. Inverser le mot III dans la chaîne
暑假第一周
每日一题——替换空格
GEO数据库中搜索数据
Arduino burning program and Arduino burning bootloader
剑指 Offer 06. 从尾到头打印链表
[three tier architecture]
剑指 Offer 05. 替换空格
STM32 --- NVIC interrupt
Stm32--- systick timer
2020-05-21
Arduino operation stm32
Example 004: for the day of the day, enter a day of a month of a year to judge the day of the year?
STM32 single chip microcomputer - bit band operation
319. Bulb switch
Run menu analysis
Search data in geo database
319. 灯泡开关
C language data type replacement