เมื่อจำเป็นต้องนับจำนวนโหนดปลายสุดใน Tree จะมีการสร้างคลาส 'Tree_structure' วิธีการเพิ่มค่ารูท และค่าย่อยอื่นๆ จะถูกกำหนด มีตัวเลือกต่างๆ ให้ผู้ใช้เลือกได้ ขึ้นอยู่กับทางเลือกของผู้ใช้ การดำเนินการจะดำเนินการกับองค์ประกอบแบบทรี
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
class Tree_structure:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root_node(self, data):
self.key = data
def add_vals(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 count_leaf_node(self):
leaf_nodes = []
self.count_leaf_node_helper_fun(leaf_nodes)
return len(leaf_nodes)
def count_leaf_node_helper_fun(self, leaf_nodes):
if self.children == []:
leaf_nodes.append(self)
else:
for child in self.children:
child.count_leaf_node_helper_fun(leaf_nodes)
tree = None
print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('count')
print('quit')
while True:
my_input = input('What operation would you like to perform ? ').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.')
continue
ref_node.add_vals(newNode)
elif operation == 'count':
if tree is None:
print('The tree is empty')
else:
count = tree.count_leaf_node()
print('The number of leaf nodes are : {}'.format(count))
elif operation == 'quit':
break ผลลัพธ์
Menu (this assumes no duplicate keys) add <data> at root add <data> below <data> count quit What operation would you like to perform ? add 78 at root What operation would you like to perform ? add 90 below 78 What operation would you like to perform ? add 8 below 78 What operation would you like to perform ? count The number of leaf nodes are : 2 What operation would you like to perform ? quit
คำอธิบาย
-
สร้างคลาส "Tree_structure" แล้ว
-
มันตั้งค่า 'คีย์' เป็น True และตั้งค่ารายการว่างให้กับลูกของ tree
-
มีฟังก์ชัน 'set_root' ที่ช่วยตั้งค่ารูทสำหรับต้นไม้
-
มีการกำหนดเมธอดชื่อ 'add_vals' ซึ่งช่วยเพิ่มองค์ประกอบให้กับทรี
-
มีการกำหนดวิธีการอื่นที่เรียกว่า 'search_val' ซึ่งช่วยในการค้นหาองค์ประกอบในทรี
-
มีการกำหนดวิธีอื่นที่ชื่อว่า 'count_leaf_nodes' ซึ่งจะช่วยให้นับโหนดลีฟของต้นไม้ได้
-
มีการกำหนดวิธีการอื่นชื่อ 'count_leaf_nodes_helper' ซึ่งเรียกใช้ฟังก์ชันที่กำหนดไว้ก่อนหน้านี้ ซึ่งเป็นฟังก์ชันแบบเรียกซ้ำ
-
มีสี่ตัวเลือกให้เลือก เช่น 'เพิ่มที่รูท', 'เพิ่มด้านล่าง', 'นับ' และ 'ออก'
-
ขึ้นอยู่กับตัวเลือกที่กำหนดโดยผู้ใช้ การดำเนินการตามลำดับจะดำเนินการ
-
เอาต์พุตนี้จะแสดงบนคอนโซล