Python深度优先遍历DFS与广度优先遍历BFS

今天药忘吃喽~ 2022-04-23 10:36 480阅读 0赞

深度优先遍历DFS与广度优先遍历BFS

以下代码块是在python3.7-32bit下成功运行的例子,其中广度优先遍历是由队列实现的,深度优先遍历是由递归和栈两种方法实现的。

  1. """ 广度优先遍历和深度优先遍历在二叉树以及图的问题上非常重要。 要深入理解这两种遍历的过程实现,先知道怎么用纸和笔比画出来。 深入理解先入先出和后入先出这两个过程,是一个二层的过程,上一层先弄的下一层也先弄为队列,上一层先弄的下一层后弄为栈。 """
  2. # 先造出来一棵简单的二叉树结构供使用
  3. class Tree:
  4. def __init__(self, list_of_three):
  5. # list_of_three [1,2,3] 根左右
  6. # print("依次输入树的根、左节点、右节点")
  7. # .node其实是当前节点的值
  8. # 面向对象思想还是挺有用的
  9. if list_of_three[0] != 0:
  10. self.node = list_of_three[0]
  11. else:
  12. self.node = "none"
  13. if list_of_three[1] != 0:
  14. self.left = list_of_three[1]
  15. else:
  16. self.left = "none"
  17. if list_of_three[2] != 0:
  18. self.right = list_of_three[2]
  19. else:
  20. self.right = "none"
  21. # 进行广度优先遍历BFS
  22. def BFS(root_node):
  23. # pop(0)和append()是队列
  24. q = []
  25. q.append(root_node)
  26. while len(q) != 0:
  27. temp = q.pop(0)
  28. print(temp.node)
  29. if temp.left != "none":
  30. q.append(temp.left)
  31. if temp.right != "none":
  32. q.append(temp.right)
  33. # 使用递归方式实现DFS
  34. def DFS_recursion(root_node):
  35. print(root_node.node)
  36. if root_node == "none":
  37. return
  38. if root_node.left != "none":
  39. DFS_recursion(root_node.left)
  40. if root_node.right != "none":
  41. DFS_recursion(root_node.right)
  42. # 使用栈来实现DFS
  43. def DFS_stack(root_node):
  44. # pop()和append()是栈,pop()就差个0与队列相比
  45. s = []
  46. if root_node == "none":
  47. return
  48. s.append(root_node)
  49. while len(s) != 0:
  50. temp = s.pop()
  51. print(temp.node)
  52. if temp.right != "none":
  53. s.append(temp.right)
  54. if temp.left != "none":
  55. s.append(temp.left)
  56. def main():
  57. # 自定义搭建了一棵二叉树
  58. node = "root"
  59. n = [i for i in range(12)]
  60. for i in range(12):
  61. n[i] = Tree([i, 0, 0])
  62. n[5] = Tree([5, n[10], n[11]])
  63. n[4] = Tree([4, n[8], n[9]])
  64. n[3] = Tree([3, n[6], n[7]])
  65. n[2] = Tree([2, n[4], n[5]])
  66. n[1] = Tree([1, n[2], n[3]])
  67. # 变量的覆盖作用,导致之前的未被更新,解释性语言,所以赋值需要从后往前
  68. print("--------------------------------------------------------------")
  69. print("基于递归的深度优先遍历:")
  70. DFS_recursion(n[1])
  71. print("--------------------------------------------------------------")
  72. print("基于栈的深度优先遍历:")
  73. DFS_stack(n[1])
  74. print("--------------------------------------------------------------")
  75. print("广度优先遍历:")
  76. BFS(n[1])
  77. print("--------------------------------------------------------------")
  78. if __name__ == "__main__":
  79. main()

发表评论

表情:
评论列表 (有 0 条评论,480人围观)

还没有评论,来说两句吧...

相关阅读