当需要查找树的所有节点的总和时,将创建一个类,该类包含设置根节点,向树中添加元素,搜索特定元素以及将树中的元素添加至的方法。找到总和,依此类推。可以创建该类的实例来访问和使用这些方法。
以下是相同的演示-
class Tree_struct:
def __init__(self, data=None):
self.key= data
self.children= []
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 sum_node(self):
my_summation = self.key
for child in self.children:
my_summation = my_summation + child.sum_node()
return my_summation
my_instance = None
print('Menu (assume no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('sum')
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
elif suboperation == 'below':
position = my_input[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
ref_node.add_node(new_node)
elif operation == 'sum':
if my_instance is None:
print('The tree is empty')
else:
my_summation = my_instance.sum_node()
print('Sum of all nodes is: {}'.format(my_summation))
elif operation == 'quit':
break
输出结果Menu (assume no duplicate keys)
add <data> at root
add <data> below <data>
sum
quit
What operation would you do ? add 5 at root
What operation would you do ? add 7 below 5
What operation would you do ? add 0 below 7
What operation would you do ? sum
Sum of all nodes is: 12
What operation would you do ? quit
创建具有必需属性的“ Tree_struct”类。
它具有一个“ init”函数,用于创建一个空列表。
定义了一个“ set_root”方法,该方法有助于设置二叉树的根值。
它有一个“ add_node”方法,可以帮助向树中添加元素。
定义了一个名为“ search_elem”的方法,该方法有助于搜索特定元素。
定义了一个名为“ sum_node”的方法,该方法有助于添加树的元素并找到总和。
创建一个实例并将其分配给“无”。
用户输入用于需要执行的操作。
根据用户的选择,执行操作。
相关输出将显示在控制台上。