美文网首页
Python深度优先与广度优先

Python深度优先与广度优先

作者: 捂不暖的石头 | 来源:发表于2017-08-25 14:27 被阅读0次

深度优先(递归实现)

def depth_tree(tree_node):
    if tree_node is not None:
        print tree_node._data
        if tree_node._left is not None:
            return depth_tree(tree_node._left)
        if tree_node._right is not None:
            return depth_tree(tree_node._right)

广度优先(队列实现)

def level_queue(root):
    if root is None:
        return
    my_queue = []
    node = root
    my_queue.append(node)
    while my_queue:
        node = my_queue.pop(0)
        print node.elem
        if node.lchild is not None:
            my_queue.append(node.lchild)
        if node.rchild is not None:
            my_queue.append(node.rchild)

相关文章

网友评论

      本文标题:Python深度优先与广度优先

      本文链接:https://www.haomeiwen.com/subject/nwpudxtx.html