이진 트리를 구성하고 요소 삽입, 요소 삭제 및 트리 요소 표시와 같은 작업을 수행해야 하는 경우 해당 클래스에 메서드가 포함된 클래스가 정의됩니다. 클래스의 인스턴스가 정의되며 이는 요소에 액세스하고 작업을 수행하는 데 사용됩니다.
아래는 동일한 데모입니다 -
예시
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):
if self.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 <data> at root')
print('add <data> below <data>')
print('remove <data>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').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]
while leaf.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('Breadth First Search traversal is : ', end='')
my_instance.bfs()
print()
else:
print('The tree is empty')
elif operation == 'quit':
break 출력
Menu (this assumes no duplicate keys) add <data> at root add <data> below <data> remove <data> display quit What would you like to do? add 5 at root What would you like to do? add 6 below 5 What would you like to do? add 8 below 6 What would you like to do? remove 8 What would you like to do? display Breadth First Search traversal is : 5 6 What would you like to do? quit
설명
-
필수 속성을 가진 'Tree_struct' 클래스가 생성됩니다.
-
빈 목록을 만드는 데 사용되는 '초기화' 기능이 있습니다.
-
트리의 루트를 지정하기 위해 'set_root'라는 또 다른 메서드가 정의되어 있습니다.
-
트리에 노드를 추가하는 데 도움이 되는 'add_node'라는 또 다른 메서드가 정의되어 있습니다.
-
특정 요소를 검색하는 데 도움이 되는 'search_node'라는 또 다른 메서드가 정의되어 있습니다.
-
트리에서 요소를 삭제하는 'remove_node'라는 메서드가 정의되어 있습니다.
-
트리에서 너비 우선 검색을 수행하는 데 도움이 되는 'bfs'라는 또 다른 메서드가 정의되어 있습니다.
-
인스턴스가 생성되어 '없음'으로 지정됩니다.
-
수행해야 하는 작업에 대해 사용자 입력을 받습니다.
-
사용자의 선택에 따라 작업이 수행됩니다.
-
관련 출력이 콘솔에 표시됩니다.