4

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?

dsolimano
  • 8,870
  • 3
  • 48
  • 63
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

4 Answers4

5

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).

mea
  • 61
  • 2
  • 1
2

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).

AlbertoPL
  • 11,479
  • 5
  • 49
  • 73
0

With recursion. But the queue is in the stack...

eKek0
  • 23,005
  • 25
  • 91
  • 119
-1

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.

e230217
  • 1
  • 1