트리의 모든 노드의 합을 구해야 할 때 클래스를 생성하고 루트 노드를 설정하고 트리에 요소를 추가하고 특정 요소를 검색하고 트리의 요소를 추가하는 메소드를 포함합니다. 합계 등을 찾습니다. 이러한 메서드에 액세스하고 사용하기 위해 클래스의 인스턴스를 만들 수 있습니다.
아래는 동일한 데모입니다 -
예시
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):
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 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' 클래스가 생성됩니다.
-
빈 목록을 만드는 데 사용되는 '초기화' 기능이 있습니다.
-
이진 트리의 루트 값을 설정하는 데 도움이 되는 'set_root' 메서드가 정의되어 있습니다.
-
트리에 요소를 추가하는 데 도움이 되는 'add_node' 메서드가 있습니다.
-
특정 요소를 검색하는 데 도움이 되는 'search_elem'이라는 메서드가 정의되어 있습니다.
-
트리의 요소를 추가하고 합계를 찾는 데 도움이 되는 'sum_node'라는 메서드가 정의되어 있습니다.
-
인스턴스가 생성되어 '없음'으로 지정됩니다.
-
수행해야 하는 작업에 대해 사용자 입력을 받습니다.
-
사용자의 선택에 따라 작업이 수행됩니다.
-
관련 출력이 콘솔에 표시됩니다.