Python程式:構建樹並執行插入、刪除和顯示操作


當需要構建二叉樹並執行諸如插入元素、刪除元素和顯示樹的元素等操作時,可以使用定義了方法的類。 定義類的例項,並將其用於訪問元素和執行操作。

以下是相同的演示 -

示例

 線上演示

class Tree_struct:
   def __init__(self, data=None, parent=None):
      self.key = data
      self.children = []
      self.parent = parent

   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 remove_node(self):
      parent = self.parent
      index = parent.children.index(self)
      parent.children.remove(self)
      for child in reversed(self.children):
         parent.children.insert(index, child)
         child.parent = parent

   def bfs(self):
      queue = [self]
      while queue != []:
         popped = queue.pop(0)
         for child in popped.children:
            queue.append(child)
         print(popped.key, end=' ')

my_instance = None

print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('remove <data>')
print('display')
print('quit')

while True:
   do = input('What would you like to do? ').split()

   operation = do[0].strip().lower()
   if operation == 'add':
      data = int(do[1])
      new_node = Tree_struct(data)
      suboperation = do[2].strip().lower()
      if suboperation == 'at':
         my_instance = new_node
      elif suboperation == 'below':
         position = do[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
         new_node.parent = ref_node
         ref_node.add_node(new_node)

   elif operation == 'remove':
      data = int(do[1])
      to_remove = my_instance.search_node(data)
      if my_instance == to_remove:
         if my_instance.children == []:
            my_instance = None
         else:
            leaf = my_instance.children[0]
            while leaf.children != []:
               leaf = leaf.children[0]
            leaf.parent.children.remove_node(leaf)
            leaf.parent = None
            leaf.children = my_instance.children
            my_instance = leaf
      else:
         to_remove.remove_node()

   elif operation == 'display':
      if my_instance is not None:
         print('Breadth First Search traversal is : ', end='')
         my_instance.bfs()
         print()
      else:
         print('The tree is empty')

   elif operation == 'quit':
      break

輸出

Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
remove <data>
display
quit
What would you like to do? add 5 at root
What would you like to do? add 6 below 5
What would you like to do? add 8 below 6
What would you like to do? remove 8
What would you like to do? display
Breadth First Search traversal is : 5 6
What would you like to do? quit

解釋

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

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

  • 定義另一個名為“set_root”的方法來指定樹的根。

  • 定義另一個名為“add_node”的方法,該方法有助於將節點新增到樹中。

  • 定義另一個名為“search_node”的方法,該方法有助於搜尋特定元素。

  • 定義一個名為“remove_node”的方法,該方法從樹中刪除元素。

  • 定義另一個名為“bfs”的方法,該方法有助於在樹上執行廣度優先搜尋。

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

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

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

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

更新於:2021年4月15日

512 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告