Python程序构造一个树并执行插入,删除,显示
当需要构造二叉树并执行诸如插入元素,删除元素和显示树的元素之类的操作时,将在类中定义方法。定义了该类的实例,该实例用于访问元素和执行操作。
以下是相同的演示-
示例
class Tree_struct:
def __init__(self, data=None, parent=None):
self.key= data
self.children= []
self.parent= parent
def set_root(self, data):
self.key= data
def add_node(self, node):
self.children.append(node)
def search_node(self, key):
ifself.key== key:
return self
for child in self.children:
temp = child.search_node(key)
if temp is not None:
return temp
return None
def remove_node(self):
parent = self.parent
index = parent.children.index(self)
parent.children.remove(self)
for child in reversed(self.children):
parent.children.insert(index, child)
child.parent = parent
def bfs(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')
my_instance = None
print('Menu (this assumes no duplicate keys)')
print('add at root')
print('add below ')
print('remove ')
print('display')
print('quit')
while True:
do = input('你想做什么? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree_struct(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
my_instance = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if my_instance is not None:
ref_node = my_instance.search_node(key)
if ref_node is None:
print('No such key.')
continue
new_node.parent = ref_node
ref_node.add_node(new_node)
elif operation == 'remove':
data = int(do[1])
to_remove = my_instance.search_node(data)
if my_instance == to_remove:
if my_instance.children == []:
my_instance = None
else:
leaf = my_instance.children[0]
whileleaf.children!= []:
leaf = leaf.children[0]
leaf.parent.children.remove_node(leaf)
leaf.parent= None
leaf.children= my_instance.children
my_instance = leaf
else:
to_remove.remove_node()
elif operation == 'display':
if my_instance is not None:
print('广度优先搜索遍历是 : ', end='')
my_instance.bfs()
print()
else:
print('The tree is empty')
elif operation == 'quit':
break输出结果
Menu (假定没有重复的键) add at root add below remove display quit 你想做什么? add 5 at root 你想做什么? add 6 below 5 你想做什么? add 8 below 6 你想做什么? remove 8 你想做什么? display 广度优先搜索遍历是 : 5 6 你想做什么? quit
解释
创建具有必需属性的“Tree_struct”类。
它具有一个“init”函数,用于创建一个空列表。
定义了另一种名为“set_root”的方法来指定树的根。
定义了另一个名为“add_node”的方法,该方法有助于将节点添加到树中。
定义了另一个名为“search_node”的方法,该方法可帮助搜索特定元素。
定义了一个名为“remove_node”的方法,该方法从树中删除元素。
定义了另一个名为“bfs”的方法,该方法有助于在树上执行广度优先搜索。
创建一个实例并将其分配给“无”。
用户输入用于需要执行的操作。
根据用户的选择,执行操作。
相关输出将显示在控制台上。