Performing Breadth First Search recursively

后端 未结 21 2621
不思量自难忘°
不思量自难忘° 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:02

    Here's a Scala 2.11.4 implementation of recursive BFS. I've sacrificed tail-call optimization for brevity, but the TCOd version is very similar. See also @snv's post.

    import scala.collection.immutable.Queue
    
    object RecursiveBfs {
      def bfs[A](tree: Tree[A], target: A): Boolean = {
        bfs(Queue(tree), target)
      }
    
      private def bfs[A](forest: Queue[Tree[A]], target: A): Boolean = {
        forest.dequeueOption exists {
          case (E, tail) => bfs(tail, target)
          case (Node(value, _, _), _) if value == target => true
          case (Node(_, l, r), tail) => bfs(tail.enqueue(List(l, r)), target)
        }
      }
    
      sealed trait Tree[+A]
      case class Node[+A](data: A, left: Tree[A], right: Tree[A]) extends Tree[A]
      case object E extends Tree[Nothing]
    }
    

提交回复
热议问题