defdfs(node): if node in visited: # already visited return visited.add(node)
# process current node # ... logic here
dfs(node.left) dfs(node.right)
DFS代码-递归写法
1 2 3 4 5 6 7 8 9
visited = set()
defdfs(node,visited): visited.add(node) # process current node here ... for next_node in node.children(): ifnot next_node in visited: dfs(next node,visited)
DFS代码-非递归写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defDFS(self,tree): if tree.root isNone: return [] visited,stack = [].[tree.root]