-
Notifications
You must be signed in to change notification settings - Fork 497
/
DepthFirstTraversal.py
executable file
·51 lines (43 loc) · 1.29 KB
/
DepthFirstTraversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def depthFirstTraversalRecursive(graph, node, visited):
if node not in visited:
visited.append(node)
childs = graph[node]
if len(childs) > 0:
for child in childs:
depthFirstTraversalRecursive(graph, child, visited)
return visited
def depthFirstTraversalIterative(graph, node):
visited = []
stack = []
stack.append(node)
while len(stack) > 0:
node = stack[-1]
if node not in visited:
visited.append(node)
childs = graph[node]
while len(childs) > 0:
# add the non-visited childs to the stack in reverse order
child = childs.pop()
if child not in visited:
stack.append(child)
else:
stack.pop()
return visited
def main():
graph = {'A': ['B', 'C', 'E'],
'B': ['D', 'F'],
'C': ['G'],
'D': [],
'E': ['F'],
'F': ['C'],
'G': []}
print("Recusrive:")
result = depthFirstTraversalRecursive(graph, 'A', [])
for node in result:
print(node)
print("Iterative:")
result2 = depthFirstTraversalIterative(graph, 'A')
for node in result2:
print(node)
if __name__ == '__main__':
main()