Can every recursion be converted into iteration?

前端 未结 17 2319
遥遥无期
遥遥无期 2020-11-22 01:59

A reddit thread brought up an apparently interesting question:

Tail recursive functions can trivially be converted into iterative functions. Other one

17条回答
  •  走了就别回头了
    2020-11-22 02:10

    • Recursive function execution flow can be represented as a tree.

    • The same logic can be done by a loop, which uses a data-structure to traverse that tree.

    • Depth-first traversal can be done using a stack, breadth-first traversal can be done using a queue.

    So, the answer is: yes. Why: https://stackoverflow.com/a/531721/2128327.

    Can any recursion be done in a single loop? Yes, because

    a Turing machine does everything it does by executing a single loop:

    1. fetch an instruction,
    2. evaluate it,
    3. goto 1.

提交回复
热议问题