使用後序遍歷實現深度優先搜尋的Python程式


當需要使用後序遍歷實現深度優先搜尋時,會建立一個包含新增元素、搜尋特定元素以及執行後序遍歷等方法的樹類。建立一個類的例項,就可以用來訪問這些方法。

以下是相同的演示 -

示例

 線上演示

class Tree_Struct:
   def __init__(self, key=None):
      self.key = key
      self.children = []

   def add_elem(self, node):
      self.children.append(node)
 
   def search_elem(self, key):
      if self.key == key:
         return self
      for child in self.children:
         temp = child.search_elem(key)
         if temp is not None:
            return temp
      return None

   def postorder_traversal(self):
      for child in self.children:
         child.postorder_traversal()
      print(self.key, end=' ')

my_instance = None

print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('dfs')
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
      else:
         position = my_input[3].strip().lower()
         key = int(position)
         ref_node = None
         if my_instance is not None:
            ref_node = my_instance.search_elem(key)
         if ref_node is None:
            print('No such key exists')
            continue
         ref_node.add_elem(new_node)

   elif operation == 'dfs':
      print('The post-order traversal is : ', end='')
      my_instance.postorder_traversal()
      print()

   elif operation == 'quit':
      break

輸出

Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
dfs
quit
What operation would you do ? add 5 at root
What operation would you do ? insert 9 below 5
What operation would you do ? insert 2 below 9
What operation would you do ? dfs
The post-order traversal is : 5
What operation would you do ? quit

解釋

  • 建立具有所需屬性的“Tree_struct”類。

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

  • 它有一個“add_elem”方法,用於將元素新增到樹中。

  • 另一個名為“postorder_traversal”的方法執行後序遍歷。

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

  • 建立一個例項並將其賦值為“None”。

  • 獲取使用者輸入,以確定需要執行的操作。

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

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

更新於: 2021年4月16日

398 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.