Let\'s say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?
Is it possible using only the call-stack
I would like to add my cents to the top answer in that if the language supports something like generator, bfs can be done co-recursively.
To begin with, @Tanzelax's answer reads:
Breadth-first traversal traditionally uses a queue, not a stack. The nature of a queue and a stack are pretty much opposite, so trying to use the call stack (which is a stack, hence the name) as the auxiliary storage (a queue) is pretty much doomed to failure
Indeed, ordinary function call's stack won't behave like a normal stack. But generator function will suspend the execution of function so it gives us the chance to yield next level of nodes' children without delving into deeper descendants of the node.
The following code is recursive bfs in Python.
def bfs(root):
yield root
for n in bfs(root):
for c in n.children:
yield c
The intuition here is: