对于广度优先遍历而言,我们可以用迭代的方法轻松求解,但是对于递归,就很难了,也很难记忆 ,因此这里给出BFS的迭代解法,这个function会根据BFS的顺序依次打印出我们访问的节点,有点小trick,代码如下:

def bfs_level_order_traversal(node): 
    if node is None:
        return None
    L = [node]
    while len(L) > 0:
        current_node = L.pop(0)
        print(current_node)
     for child in current_node.children:   if child is not None:    L.append(child)

这算法一看就懂,无需多言。linux曾经说道:“talk is cheap ,show me the code”,我们要充分落实linux的思想,才能学好计算机。

相关文章:

  • 2021-06-21
  • 2021-08-23
  • 2022-01-17
  • 2021-12-27
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-24
  • 2021-06-11
  • 2021-09-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案