As I remember and checked, the usual way for traversing a tree or crawling the web breadth first (BFS) is by using a queue. Is there actually a way to implement it not using a queue?
-
What would be the purpose of not using a queue? – AlbertoPL May 13 '09 at 03:22
-
just to know different ways to implement it – nonopolarity Jun 03 '10 at 07:08
-
Maybe my comment is outdated but there really is way to do that. http://stackoverflow.com/a/2549825/2198656 – Herrington Darkholme Feb 16 '14 at 11:36
4 Answers
I know this question is old now, but I just wanted to answer. You can do this with arrays, linked lists (or any other linear container) and without recursion. Keep two containers, old
and new
, and swap old
with new
when you traverse all of the items in old
. Very similar to the implementation with queue.
In Python it would look like:
def breadth_first(root):
if not root:
return
old = []
new = []
old.append(root)
while old:
for n in old:
process(n) # Do something
if n.left:
new.append(n.left)
if n.right:
new.append(n.right)
old = new
new = []
Runtime complexity would be the same as the queue implementation, O(n).

- 61
- 2
- 1
You really should be using a queue, as its easier to implement. Also, a queue allows for multiple machines to work together (one queues site while another pops sites off of the queue to traverse).
The only other way I see to do this is by using recursion (much more difficult, and uses only marginally either more or less memory).

- 11,479
- 5
- 49
- 73
-
-
see http://stackoverflow.com/questions/69192/using-stack-as-queue . Essentially, you can use two stacks. – AlbertoPL Oct 12 '10 at 03:37
-
The link you showed implemented a queue with two stacks. But how to convert that idea into a recursive implementation of BFS? – max Oct 30 '16 at 16:30
With recursion. But the queue is in the stack...

- 23,005
- 25
- 91
- 119
-
is there like a simple pseudo code some where that can implement BFS using recursion? – nonopolarity May 13 '09 at 03:44
-
1I wonder about this too. How do you want to efficiently replace a queue by using the callstack? – Lucero Jun 29 '09 at 14:01
if you care about ordering, use queue. queue preserves the insertion ordering. or you can use list's implementation, say, two array lists, to alternate. But fundamentally, list preserves ordering too.
if you don't care about ordering, you can use any set implementations. sets doesn't preserve this ordering.
For example, in BFS implementation, if you don't care the ordering of nodes, you can use two sets, old and new to alternate, rather than a queue.

- 1
- 1