使用递归进行深度优先二叉树搜索的 Python 程序
当需要使用递归在树上执行深度优先搜索时,定义了一个类,并在其上定义了有助于执行广度优先搜索的方法。
以下是相同的演示-
示例
class BinaryTree_struct:
def __init__(self, key=None):
self.key= key
self.left= None
self.right= None
def set_root(self, key):
self.key= key
def insert_at_left(self, new_node):
self.left= new_node
def insert_at_right(self, new_node):
self.right= new_node
def search_elem(self, key):
ifself.key== key:
return self
ifself.leftis not None:
temp = self.left.search(key)
if temp is not None:
return temp
ifself.rightis not None:
temp = self.right.search(key)
return temp
return None
def depth_first_search(self):
print('entering {}...'.format(self.key))
ifself.leftis not None:
self.left.depth_first_search()
print('at {}...'.format(self.key))
ifself.rightis not None:
self.right.depth_first_search()
print('leaving {}...'.format(self.key))
btree_instance = None
print('Menu (no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('dfs')
print('quit')
while True:
my_input = input('What would you like to do? ').split()
op = my_input[0].strip().lower()
if op == 'insert':
data = int(my_input[1])
new_node = BinaryTree_struct(data)
sub_op = my_input[2].strip().lower()
if sub_op == 'at':
btree_instance = new_node
else:
position = my_input[4].strip().lower()
key = int(position)
ref_node = None
if btree_instance is not None:
ref_node = btree_instance.search_elem(key)
if ref_node is None:
print('No such key.')
continue
if sub_op == 'left':
ref_node.insert_at_left(new_node)
elif sub_op == 'right':
ref_node.insert_at_right(new_node)
elif op == 'dfs':
print('depth-first search traversal:')
if btree_instance is not None:
btree_instance.depth_first_search()
print()
elif op == 'quit':
break输出结果Menu (no duplicate keys) insert at root insert left of insert right of dfs quit What would you like to do? insert 5 at root What would you like to do? insert 6 left of 5 What would you like to do? insert 8 right of 5 What would you like to do? dfs depth-first search traversal: entering 5... entering 6... at 6... leaving 6... at 5... entering 8... at 8... leaving 8... leaving 5... What would you like to do? quit Use quit() or Ctrl-D (i.e. EOF) to exit
解释
创建了具有所需属性的“BinaryTree_struct”类。
它有一个“init”函数,用于将“左”和“右”节点分配给“无”。
另一个名为“set_root”的方法被定义为指定树的根。
定义了另一个名为“insert_at_left”的方法,它有助于将节点添加到树的左侧。
定义了另一个名为“insert_at_right”的方法,它有助于将节点添加到树的右侧。
另一种名为“search_elem”的方法被定义为帮助搜索特定元素。
定义了一个名为“depth_first_search”的方法,它有助于在二叉树上执行深度优先搜索。
类的一个实例被创建并分配给“无”。
给了一个菜单。
用户输入用于需要执行的操作。
根据用户的选择,执行操作。
相关输出显示在控制台上。