学以致用

focus on Python , C++, and some interest in Go and R

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

使用python实现的树遍历,包括宽度优先和深度优先

ef dfs():
    tree = {
        'A': ['B', 'C'],
        'B': ['D', 'E'],
        'C': ['F', 'G'],
        'D': ['H', 'I'],
        'E': [],
        'F': [],
        'G': [],
        'H': [],
        'I': []
    }
    leaf = []
    to_crawl = deque(['A'])
    while to_crawl:
        current = to_crawl.popleft()
        print current, to_crawl
        children = tree[current]
        if len(children)> 0:
            # width first
            # to_crawl.extend(children)
            # depth first
            to_crawl.extendleft(children[::-1])
            print to_crawl
        else:
            leaf.append(current)
    print leaf

对于图的遍历稍微调整一下即可,主要是图需要考虑的重复遍历的问题,所以需要记录已经遍历过哪些节点,每次获得新的children之后减去已遍历过的节点即可

posted on 2015-04-04 09:29  Jerry.Kwan  阅读(1019)  评论(0编辑  收藏  举报