How to convert a recursive function to use a stack?

前端 未结 4 2004
独厮守ぢ
独厮守ぢ 2020-12-05 06:00

Suppose that I have a tree to traverse using a Depth First Search, and that my algorithm for traversing it looks something like this:

algorithm search(NODE):         


        
4条回答
  •  醉话见心
    2020-12-05 06:07

    You change this to use a stack like so:

    algorithm search(NODE):
      createStack()
      addNodeToStack(NODE)
    
      while(stackHasElements)
          NODE = popNodeFromStack()
          doSomethingWith(NODE)
          for each node CHILD connected to NODE:
             addNodeToStack(CHILD)
    

    As for your second question:

    In many cases, there are a lot of local variables; where can they be stored?

    These really can be kept in the same location as they were originally. If the variables are local to the "doSomethingWith" method, just move them into that, and refactor that into a separate method. The method doesn't need to handle the traversal, only the processing, and can have it's own local variables this way that work in its scope only.

提交回复
热议问题