เมื่อจำเป็นต้องได้รับผลรวมของโหนดทั้งหมดใน Tree คลาส 'Tree_structure' จะถูกสร้างขึ้น วิธีการตั้งค่ารูท และเพิ่มค่าอื่นๆ จะถูกกำหนด นอกจากนี้ยังมีวิธีการกำหนดผลรวมขององค์ประกอบทั้งหมดของโครงสร้างต้นไม้ มีตัวเลือกต่างๆ ให้ผู้ใช้เลือกได้ ขึ้นอยู่กับทางเลือกของผู้ใช้ การดำเนินการจะดำเนินการกับองค์ประกอบแบบทรี
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
class Tree_structure:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add_values(self, node):
self.children.append(node)
def search_val(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search(key)
if temp is not None:
return temp
return None
def summation_nodes(self):
sum_val = self.key
for child in self.children:
sum_val = sum_val + child.summation_nodes()
return sum_val
tree = None
print('Menu (no duplicate keys allowed)')
print('add <data> at root')
print('add <data> below <data>')
print('summation')
print('quit')
while True:
my_input = input('What would you like to do? ').split()
operation = my_input[0].strip().lower()
if operation == 'add':
data = int(my_input[1])
newNode = Tree_structure(data)
sub_op = my_input[2].strip().lower()
if sub_op == 'at':
tree = newNode
elif sub_op == 'below':
my_pos = my_input[3].strip().lower()
key = int(my_pos)
ref_node = None
if tree is not None:
ref_node = tree.search_val(key)
if ref_node is None:
print('No such key exists')
continue
ref_node.add_values(newNode)
elif operation == 'summation':
if tree is None:
print('The tree is empty')
else:
summation_val = tree.summation_nodes()
print('Sum of all the nodes is : {}'.format(summation_val))
elif operation == 'quit':
break ผลลัพธ์
Menu (no duplicate keys allowed) add <data> at root add <data> below <data> summation quit What would you like to do? add 56 at root What would you like to do? add 45 below 56 What would you like to do? add 23 below 56 What would you like to do? summation Sum of all the nodes is : 124 What would you like to do?
คำอธิบาย
-
สร้างคลาส "Tree_structure" แล้ว
-
มันตั้งค่า 'คีย์' เป็น True และตั้งค่ารายการว่างให้กับลูกของ tree
-
มีฟังก์ชัน 'set_root' ที่ช่วยตั้งค่ารูทสำหรับต้นไม้
-
มีการกำหนดเมธอดชื่อ 'add_vals' ซึ่งช่วยเพิ่มองค์ประกอบให้กับทรี
-
มีการกำหนดวิธีการอื่นที่เรียกว่า 'search_val' ซึ่งช่วยในการค้นหาองค์ประกอบในทรี
-
มีการกำหนดวิธีการอื่นที่เรียกว่า 'summation_nodes' ซึ่งช่วยให้ได้ผลรวมขององค์ประกอบ/โหนดทั้งหมดของทรี
-
เป็นฟังก์ชันแบบเรียกซ้ำ
-
มีสี่ตัวเลือกให้เลือก เช่น 'เพิ่มที่รูท', 'เพิ่มด้านล่าง', 'รวม' และ 'ออก'
-
ขึ้นอยู่กับตัวเลือกที่กำหนดโดยผู้ใช้ การดำเนินการตามลำดับจะดำเนินการ
-
เอาต์พุตนี้จะแสดงบนคอนโซล