python 树遍历

时间:2022-01-13 16:02:27

使用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之后减去已遍历过的节点即可