使用递归的深度优先二叉树搜索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):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search(key)
return temp
return None
def depth_first_search(self):
print('entering {}...'.format(self.key))
if self.left is not None:
self.left.depth_first_search()
print('at {}...'.format(self.key))
if self.right is not None:
self.right.depth_first_search()
print('leaving {}...'.format(self.key))
btree_instance = None
print('Menu (no duplicate keys)')
print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
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 <data> at root insert <data> left of <data> insert <data> right of <data> 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’函数,用于将‘left’和‘right’节点赋值为‘None’。
定义另一个名为‘set_root’的方法来指定树的根节点。
定义另一个名为‘insert_at_left’的方法,用于帮助将节点添加到树的左侧。
定义另一个名为‘insert_at_right’的方法,用于帮助将节点添加到树的右侧。
定义另一个名为‘search_elem’的方法,用于帮助搜索特定元素。
定义了一个名为‘depth_first_search’的方法,用于帮助对二叉树执行深度优先搜索。
创建类的实例并将其赋值为‘None’。
提供一个菜单。
获取用户输入,以确定需要执行的操作。
根据用户的选择执行操作。
在控制台上显示相关的输出。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP