Skip to content
Code ReadingWalking with a Stack
Predict the Output

Walking with a Stack

A depth-first walk with a stack. In what order are the nodes visited? Write what is printed.
1graph = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": []}
2seen, stack, order = {"A"}, ["A"], []
3while stack:
4 node = stack.pop()
5 order.append(node)
6 for nxt in graph[node]:
7 if nxt not in seen:
8 seen.add(nxt)
9 stack.append(nxt)
10print("".join(order))