使用后序实现深度优先搜索遍历的 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):
ifself.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 at root')
print('add below ')
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 at root add below 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”的方法,它有助于搜索特定元素。
创建一个实例并将其分配给“无”。
用户输入用于需要执行的操作。
根据用户的选择,执行操作。
相关输出显示在控制台上。