使用后序遍历实现深度优先搜索的Python程序
当需要使用后序遍历实现深度优先搜索时,会创建一个包含添加元素、搜索特定元素以及执行后序遍历等方法的树类。创建一个类的实例,就可以用来访问这些方法。
以下是相同的演示 -
示例
class Tree_Struct:
def __init__(self, key=None):
self.key = key
self.children = []
def add_elem(self, node):
self.children.append(node)
def search_elem(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search_elem(key)
if temp is not None:
return temp
return None
def postorder_traversal(self):
for child in self.children:
child.postorder_traversal()
print(self.key, end=' ')
my_instance = None
print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('dfs')
print('quit')
while True:
my_input = input('What operation would you do ? ').split()
operation = my_input[0].strip().lower()
if operation == 'add':
data = int(my_input[1])
new_node = Tree_Struct(data)
suboperation = my_input[2].strip().lower()
if suboperation == 'at':
my_instance = new_node
else:
position = my_input[3].strip().lower()
key = int(position)
ref_node = None
if my_instance is not None:
ref_node = my_instance.search_elem(key)
if ref_node is None:
print('No such key exists')
continue
ref_node.add_elem(new_node)
elif operation == 'dfs':
print('The post-order traversal is : ', end='')
my_instance.postorder_traversal()
print()
elif operation == 'quit':
break输出
Menu (this assumes no duplicate keys) add <data> at root add <data> below <data> dfs quit What operation would you do ? add 5 at root What operation would you do ? insert 9 below 5 What operation would you do ? insert 2 below 9 What operation would you do ? dfs The post-order traversal is : 5 What operation would you do ? quit
解释
创建具有所需属性的“Tree_struct”类。
它有一个“init”函数,用于创建一个空列表。
它有一个“add_elem”方法,用于将元素添加到树中。
另一个名为“postorder_traversal”的方法执行后序遍历。
定义了一个名为“search_elem”的方法,用于搜索特定元素。
创建一个实例并将其赋值为“None”。
获取用户输入,以确定需要执行的操作。
根据用户的选择,执行操作。
在控制台上显示相关的输出。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP