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


當需要找到樹中所有節點的總和時,會建立一個類,它包含設定根節點、向樹中新增元素、搜尋特定元素以及新增樹的元素以查詢總和等方法。可以建立類的例項來訪問和使用這些方法。

以下是相同內容的演示 -

示例

 線上演示

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”類。

  • 它具有一個“init”函式,用於建立空列表。

  • 定義了一個“set_root”方法,用於設定二叉樹的根值。

  • 它有一個“add_node”方法,用於幫助向樹中新增元素。

  • 定義了一個名為“search_elem”的方法,用於幫助搜尋特定元素。

  • 定義了一個名為“sum_node”的方法,用於幫助新增樹的元素並找到總和。

  • 建立一個例項並將其分配給“None”。

  • 獲取使用者輸入以執行所需的運算。

  • 根據使用者的選擇執行操作。

  • 在控制檯上顯示相關輸出。

更新於: 2021年4月17日

180次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.