Performing Breadth First Search recursively

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

    I would like to add my cents to the top answer in that if the language supports something like generator, bfs can be done co-recursively.

    To begin with, @Tanzelax's answer reads:

    Breadth-first traversal traditionally uses a queue, not a stack. The nature of a queue and a stack are pretty much opposite, so trying to use the call stack (which is a stack, hence the name) as the auxiliary storage (a queue) is pretty much doomed to failure

    Indeed, ordinary function call's stack won't behave like a normal stack. But generator function will suspend the execution of function so it gives us the chance to yield next level of nodes' children without delving into deeper descendants of the node.

    The following code is recursive bfs in Python.

    def bfs(root):
      yield root
      for n in bfs(root):
        for c in n.children:
          yield c
    

    The intuition here is:

    1. bfs first will return the root as first result
    2. suppose we already have the bfs sequence, the next level of elements in bfs is the immediate children of previous node in the sequence
    3. repeat the above two procedures

提交回复
热议问题