广度优先遍历的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的思想,才能学好计算机。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM