Performing Breadth First Search recursively

后端 未结 21 2516
不思量自难忘°
不思量自难忘° 2020-11-28 01:12

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

21条回答
  •  失恋的感觉
    2020-11-28 02:05

    I couldn't find a way to do it completely recursive (without any auxiliary data-structure). But if the queue Q is passed by reference, then you can have the following silly tail recursive function:

    BFS(Q)
    {
      if (|Q| > 0)
         v <- Dequeue(Q)
         Traverse(v)
         foreach w in children(v)
            Enqueue(Q, w)    
    
         BFS(Q)
    }
    

提交回复
热议问题