Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

트리에 있는 모든 노드의 합을 찾는 Python 프로그램

<시간/>

Tree에 있는 모든 노드의 합을 구해야 하는 경우 'Tree_structure' 클래스를 생성하고 루트 값을 설정하고 다른 값을 추가하는 메소드를 정의합니다. 또한 트리 구조의 모든 요소의 합을 결정하는 방법이 있습니다. 사용자가 선택할 수 있는 다양한 옵션이 제공됩니다. 사용자의 선택에 따라 Tree 요소에 대해 작업을 수행합니다.

아래는 동일한 데모입니다 -

예시

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' 클래스가 생성됩니다.

  • 'key'를 True로 설정하고 빈 목록을 트리의 자식으로 설정합니다.

  • 트리의 루트 값을 설정하는 데 도움이 되는 'set_root' 기능이 있습니다.

  • 트리에 요소를 추가하는 데 도움이 되는 'add_vals'라는 메서드가 정의되어 있습니다.

  • 트리에서 요소를 검색하는 데 도움이 되는 'search_val'이라는 또 다른 메서드가 정의되어 있습니다.

  • 트리의 모든 요소/노드의 합계를 구하는 데 도움이 되는 'summation_nodes'라는 또 다른 메서드가 정의되어 있습니다.

  • 재귀 함수입니다.

  • '루트에 추가', '아래에 추가', '합계' 및 '종료'와 같은 4가지 옵션이 제공됩니다.

  • 사용자가 부여한 옵션에 따라 각각의 작업을 수행합니다.

  • 이 출력은 콘솔에 표시됩니다.