Predict the output
What does this print?
tree = {"a": ["b", "c"], "b": ["d"], "c": [], "d": []}
order = []
stack = ["a"]
while stack:
node = stack.pop()
order.append(node)
stack.extend(reversed(tree[node]))
print(order)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['a', 'b', 'd', 'c']
Right: pushing children in reverse keeps the recursive pre-order.
The explicit stack reproduces the same visits as the recursive walk, without using the call stack.
Why not the others?
- B ['a', 'c', 'b', 'd']. That is the order without reversing the children.
- C ['a', 'b', 'c', 'd']. That is level order, which needs a queue.