广度优先遍历的Python实现

对于广度优先遍历而言,我们可以用迭代的方法轻松求解,但是对于递归,就很难了,也很难记忆 ,因此这里给出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的思想,才能学好计算机。

原文地址:https://www.cnblogs.com/geeksongs/p/14631759.html