4

Are there any advantages to writing a BFS tree-traversal algorithm recursively vs iteratively? It seems to me iterative is the way to go since it can be implemented in a simple loop:

  1. Enqueue root node
  2. Dequeue node and examine
  3. Enqueue its children
  4. Go to step 2

Is there any advantage to recursion? It seems more complex with no advantages.

Thanks in advance...

Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135
  • 3
    [process is not the same as procedure](https://stackoverflow.com/questions/17254240/sicp-recursive-process-vs-iterative-process-using-a-recursive-procedure-to-gene) – recursive *procedures* don't necessarily yield a recursive *process*. – Mulan Mar 07 '18 at 20:32
  • 3
    You seem to have answered your own question : "It seems more complex with no advantages". I see no advantages either, and all the implementations I have seen are queue based. – Some Guy Mar 07 '18 at 20:32
  • How would you even implement it in recursion? recursion is just stack behind the scene, where BFS is queue. I don't think it's even possible, without some wizardy – Shihab Shahriar Khan Mar 09 '18 at 16:45

1 Answers1

0

When considering algorithms, we mainly consider time complexity and space complexity. The time complexity of iterative BFS is O(|V|+|E|), where |V| is the number of vertices and |E| is the number of edges in the graph. So does recursive BFS. And the space complexity of iterative BFS is O(|V|). So does recursive BFS.

From the perspective of time complexity and space complexity, there is no difference between these two algorithms. Since iterative BFS is easy to understand, it is not surprising that people prefer iterative BFS.

rabbit
  • 74
  • 1
  • 4