使用BFS遍历显示树节点的Python程序


当需要使用广度优先搜索遍历显示树的节点时,会创建一个类,其中包含设置根节点、向树中添加元素、搜索特定元素、执行“bfs”(广度优先搜索)等方法。可以创建类的实例来访问和使用这些方法。

下面是相同内容的演示 -

示例

 在线演示

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 bfs_operation(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 (assume no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('bfs')
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 == 'bfs':
      if my_instance is None:
         print('The tree is empty')
      else:
         print('Breadth First Search traversal is : ', end='')
         my_instance.bfs_operation()
         print()

   elif operation == 'quit':
      break

输出

Menu (assume no duplicate keys)
add <data> at root
add <data> below <data>
bfs
quit
What operation would you do ? add 6 at root
What operation would you do ? add 4 below 6
What operation would you do ? add 9 below 4
What operation would you do ? bfs
Breadth First Search traversal is : 6 4 9
What operation would you do ? quit

解释

  • 创建了具有所需属性的“Tree_struct”类。

  • 它有一个“init”函数,用于创建空列表。

  • 定义了一个“set_root”方法,用于设置二叉树的根值。

  • 它有一个“add_node”方法,用于向树中添加元素。

  • 定义了一个名为“search_elem”的方法,用于搜索特定元素。

  • 定义了一个名为“bfs_operation”的方法,用于对树执行广度优先搜索遍历。

  • 创建一个实例并将其分配给“None”。

  • 获取用户输入以执行所需的操作。

  • 根据用户的选择执行操作。

  • 在控制台上显示相关输出。

更新于: 2021年4月17日

782 次查看

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.