使用 BFS 遍历创建树的镜像副本并显示的 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_to_left(self, new_node):
self.left= new_node
def insert_to_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_elem(key)
if temp is not None:
return temp
ifself.rightis not None:
temp = self.right.search_elem(key)
return temp
return None
def copy_mirror(self):
mirror = BinaryTree_struct(self.key)
ifself.rightis not None:
mirror.left = self.right.copy_mirror()
ifself.leftis not None:
mirror.right = self.left.copy_mirror()
return mirror
def bfs(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
ifpopped.leftis not None:
queue.append(popped.left)
ifpopped.rightis not None:
queue.append(popped.right)
print(popped.key, end=' ')
my_instance = None
print('Menu (this assumes no duplicate keys)')
print('insert at root')
print('insert left of ')
print('insert right of ')
print('mirror')
print('quit')
while True:
my_input = input('What operation would you do ? ').split()
operation = my_input[0].strip().lower()
if operation == 'insert':
data = int(my_input[1])
new_node = BinaryTree_struct(data)
suboperation = my_input[2].strip().lower()
if suboperation == 'at':
my_instance = new_node
else:
position = my_input[4].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
if suboperation == 'left':
ref_node.insert_to_left(new_node)
elif suboperation == 'right':
ref_node.insert_to_right(new_node)
elif operation == 'mirror':
if my_instance is not None:
print('Creating a mirror copy...')
mirror = my_instance.copy_mirror()
print('The breadth first search traversal of original tree is : ')
my_instance.bfs()
print()
print('The breadth first traversal of mirror is : ')
mirror.bfs()
print()
elif operation == 'quit':
break输出结果Menu (this assumes no duplicate keys) insert at root insert left of insert right of mirror quit What operation would you do ? insert 6 at root What operation would you do ? insert 9 left of 6 What operation would you do ? insert 4 right of 6 What operation would you do ? mirror Creating a mirror copy... The breadth first search traversal of original tree is : 6 9 4 The breadth first traversal of mirror is : 6 4 9 What operation would you do ?quit Use quit() or Ctrl-D (i.e. EOF) to exit
解释
创建了具有所需属性的“BinaryTree_struct”类。
它有一个“init”函数,用于将左右节点分配给“None”。
定义了一个“set_root”方法,帮助将根节点分配给一个值。
它有一个“insert_to_left”方法,可以帮助向树的左节点添加元素。
它有一个“insert_to_right”方法,可以帮助将元素添加到树的正确节点。
它有一个“bfs”方法,可以帮助在树上执行广度优先搜索遍历。
定义了一个名为“search_elem”的方法,它有助于搜索特定元素。
它有一个“copy_mirror”方法,可以帮助创建二叉树的副本。
创建一个实例并将其分配给“无”。
用户输入用于需要执行的操作。
根据用户的选择,执行操作。
相关输出显示在控制台上。