recursion using only heap area

前端 未结 6 1642
你的背包
你的背包 2021-02-10 08:51

Are there examples of recursion using only heap area?

6条回答
  •  名媛妹妹
    2021-02-10 09:17

    I do it this way :

    1. implement a Queue as a singly-linked list of (object, state) pairs
    2. Insert a root (object, state) pair indicating where the recursion is to begin

    then...

    1. For each (object, state) node in the Queue:
    2. | Call object.Recurse (state)
    3. | Object processes the state and adds child nodes/states to the Queue as necessary
    4. Move to next pair until end of Queue

    Usually, I implement this as a utility class "Recursor" Objects implement the interface "IRecursable"

    The Recursor class can be asked to recurse Depth-First or Width-First.

    My implementation also calls RecursionBegin() and RecursionEnd() on the root node, so that the class being recursed can handle any initialisation and cleanup code required.

    The recursed class can also have the root notified of each called peer - allowing it to see :

    RecursionBegin() - Called once, before recursion starts.
    RecursionElement() - Called multiple times (optional).
    RecursionEnd() - Called once, after recursion ends.

    These methods are a part of the IRecursable interface and can be overridden to allow the class to be flexible in how it uses the recurser.

    But there is a more concise method

    Sometimes I move these utilities into a single class called Recursable that combines the features of class Recursor and interface IRecursable… or combine them fully into the object class meaning that the class to be recursed becomes self-recursable, without any need for supporting classes.

    Hope that helps someone make a start on converting Recursive algorithms to Heap-based algorithms... and avoid clobbering the stack or causing nasty Stack-Overflows

    TBH, recursion is evil and should be avoided like the plague! (except where your language allows true tail-call recursion)

    … respect the Stack, it is a precious resource!!!

提交回复
热议问题