河内塔 - JavaScript - 很好的部分

Mik*_*iaz 8 javascript algorithm recursion

我已经看到关于递归函数的其他问题,我已经阅读了回复,但我仍然无法让算法点击我的脑袋

var hanoi = function (disc, src, aux, dst) {

  if (disc > 0) {
    hanoi(disc - 1, src, dst, aux);
   document.write('Move disc ' + disc + ' from ' + src + ' to ' + dst);
    hanoi(disc - 1, aux, src, dst);
  }
}

hanoi(3, 'Src', 'Aux', 'Dst');
Run Code Online (Sandbox Code Playgroud)

document.write(...)是如何运行的.我的逻辑是我们第一次运行功能光盘> 3.然后我们递归调用该函数再次跳过下面的所有内容,那么document.write如何有机会运行?

我理解递归(完成了基本的例子),但我仍然看不出你是如何获得输出的.如果有一种方法,我可以直观地运行它并看到它在行动,这将有所帮助.

Ted*_*opp 22

您可以想到作为调用树会发生什么(时间从上到下):

hanoi(3, ...) =>
 |-> hanoi(2, ...) =>
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |    |-> document.write(...)
 |    |-> hanoi(1, ...) =>
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |    |-> document.write(...)
 |    |    |-> hanoi(0, ...) =>
 |    |    |    \-> (does nothing)
 |    |  <-/ [hanoi(1, ...) finished]
 |  <-/ [hanoi(2, ...) finished]
 |-> document.write(...) [halfway done!]
 |-> hanoi(2, ...) =>
 |    \-> [same pattern as the first time, with different data]
 \-> [hanoi(3, ...) finished]
Run Code Online (Sandbox Code Playgroud)