当前位置:网站首页>[daiy4] jz32 print binary tree from top to bottom
[daiy4] jz32 print binary tree from top to bottom
2022-07-05 08:43:00 【strawberry47】
subject
Print each node of the binary tree from top to bottom without branches , The nodes of the same layer are printed from left to right . For example, the input {8,6,10,#,#,2,1}, As shown in the following figure, the example binary tree , Print in turn 8,6,10,2,1( Empty nodes do not print , skip ), Please store the printed results in an array , return .
Ideas
You can use the idea of queue :
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
answer
There is a recursive idea in the answer , I still don't quite understand what's going on
import queue
class Solution:
def traverse(self, root: TreeNode, res: List[List[int]], depth: int):
if root:
# A new layer
if len(res) < depth:
row = []
res.append(row)
row.append(root.val)
# Read the one-dimensional array of this layer , Add the element to the end
else:
row = res[depth -1]
row.append(root.val)
else:
return
# Remember to add the depth when recursing left and right 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)
# Add one-dimensional array
for i in temp:
for j in i:
res.append(j)
return res
边栏推荐
- [noi simulation] juice tree (tree DP)
- Esp8266 interrupt configuration
- MATLAB skills (28) Fuzzy Comprehensive Evaluation
- js异步错误处理
- Arduino burning program and Arduino burning bootloader
- Example 007: copy data from one list to another list.
- Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
- 319. 灯泡开关
- Typical low code apaas manufacturer cases
- Arduino+a4988 control stepper motor
猜你喜欢
Matlab tips (28) fuzzy comprehensive evaluation
leetcode - 445. Add two numbers II
【三层架构】
Halcon Chinese character recognition
Example 009: pause output for one second
Redis实现高性能的全文搜索引擎---RediSearch
Xrosstools tool installation for X-Series
My university
Example 003: a complete square is an integer. It is a complete square after adding 100, and it is a complete square after adding 168. What is the number?
猜谜语啦(9)
随机推荐
暑假第一周
猜谜语啦(6)
EA introduction notes
皮尔森相关系数
287. 寻找重复数-快慢指针
Is the security account given by Yixue school safe? Where can I open an account
Hello everyone, welcome to my CSDN blog!
Search data in geo database
My university
IT冷知识(更新ing~)
TypeScript手把手教程,简单易懂
【NOI模拟赛】汁树(树形DP)
【三层架构】
Halcon shape_ trans
[牛客网刷题 Day4] JZ55 二叉树的深度
12、动态链接库,dll
整形的分类:short in long longlong
Sword finger offer 09 Implementing queues with two stacks
Latex improve
猜谜语啦(4)