Python程式查詢樹中所有節點的和


當需要獲取樹中所有節點的和時,會建立一個名為“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”類。

  • 它將“key”設定為True,並將一個空列表設定為樹的子節點。

  • 它具有一個“set_root”函式,有助於為樹設定根值。

  • 定義了一個名為“add_vals”的方法,有助於將元素新增到樹中。

  • 定義了一個名為“search_val”的方法,有助於在樹中搜索元素。

  • 定義了一個名為“summation_nodes”的方法,有助於獲取樹中所有元素/節點的和。

  • 這是一個遞迴函式。

  • 提供了四個選項,例如“在根節點新增”、“在下方新增”、“求和”和“退出”。

  • 根據使用者提供的選項,執行相應操作。

  • 此輸出顯示在控制檯上。

更新於: 2021年4月15日

337 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告