使用递归进行深度优先二叉树搜索的 Python 程序
pythonserver side programmingprogramming更新于 2023/12/23 11:26:00
当需要使用递归对树进行深度优先搜索时,会定义一个类,并在其上定义有助于执行广度优先搜索的方法。
下面是相同的演示 −
示例
class BinaryTree_struct: def __init__(self, key=None): self.key = key self.left = None self.right = None def set_root(self, key): self.key = key def insert_at_left(self, new_node): self.left = new_node def insert_at_right(self, new_node): self.right = new_node def search_elem(self, key): if self.key == key: return self if self.left is not None: temp = self.left.search(key) if temp is not None: return temp if self.right is not None: temp = self.right.search(key) return temp return None def depth_first_search(self): print('entering {}...'.format(self.key)) if self.left is not None: self.left.depth_first_search() print('at {}...'.format(self.key)) if self.right is not None: self.right.depth_first_search() print('leaving {}...'.format(self.key)) btree_instance = None print('Menu (no duplicate keys)') print('insert <data> at root') print('insert <data> left of <data>') print('insert <data> right of <data>') print('dfs') print('quit') while True: my_input = input('What would you like to do? ').split() op = my_input[0].strip().lower() if op == 'insert': data = int(my_input[1]) new_node = BinaryTree_struct(data) sub_op = my_input[2].strip().lower() if sub_op == 'at': btree_instance = new_node else: position = my_input[4].strip().lower() key = int(position) ref_node = None if btree_instance is not None: ref_node = btree_instance.search_elem(key) if ref_node is None: print('No such key.') continue if sub_op == 'left': ref_node.insert_at_left(new_node) elif sub_op == 'right': ref_node.insert_at_right(new_node) elif op == 'dfs': print('depth-first search traversal:') if btree_instance is not None: btree_instance.depth_first_search() print() elif op == 'quit': break
输出
Menu (no duplicate keys) insert <data> at root insert <data> left of <data> insert <data> right of <data> dfs quit What would you like to do? insert 5 at root What would you like to do? insert 6 left of 5 What would you like to do? insert 8 right of 5 What would you like to do? dfs depth-first search traversal: entering 5... entering 6... at 6... leaving 6... at 5... entering 8... at 8... leaving 8... leaving 5... What would you like to do? quit Use quit() or Ctrl-D (i.e. EOF) to exit
解释
创建具有所需属性的 ‘BinaryTree_struct’ 类。
它有一个 ‘init’ 函数,用于将 ‘left’ 和 ‘right’ 节点分配给 ‘None’。
定义了另一个名为 ‘set_root’ 的方法来指定树的根。
定义了另一个名为 ‘insert_at_left’ 的方法,它有助于在树的左侧添加节点。
定义了另一个名为 ‘insert_at_right’ 的方法,它有助于在树的右侧添加节点。
定义了另一个名为 ‘search_elem’ 的方法定义了一个方法,用于帮助搜索特定元素。
定义了一个名为‘depth_first_search’的方法,用于在二叉树上执行深度优先搜索。
创建该类的一个实例并将其分配给‘None’。
给出一个菜单。
获取用户输入以执行需要执行的操作。
根据用户的选择执行操作。
相关输出显示在控制台上。