了解print语句的双递归

时间:2017-04-13 12:30:29

标签: java recursion

我理解递归时它只被调用一次,当有两个时,我会理解递归,因为一个递归必须先完成,或者在第二个递归之前完成。

我正在努力了解河内之塔,但我真正不理解的是当使用print语句进行两次递归时,读取代码行的顺序。

有人可以简单地打破订单吗?我创建了这个简单的例子(其中test(3);)

为什么print语句会运行?,它是不是立即被调用了?

public static void test(int n){

    if(n>0){
        test(n-2);    
        test(n-1);
        System.out.println("print " + n); 
    }
}

2 个答案:

答案 0 :(得分:0)

您的代码不是TOH的精确实现。

这里是你的代码语句的递归树和执行顺序(看到它相信它):

设n = 4

                 4

       /                  \
      2                    3
  /      \            /         \
 0        1           1          2
       /     \      /   \     /     \
      -1      0    -1    0   0       1
                                   /   \
                                  -1    0

test(4)
test(2)
test(0)
test(1)
test(-1)
test(0)
print(1)
print(2)
test(3)
test(1)
test(-1)
test(0)
print(1)
test(2)
test(0)
test(1)
test(-1)
test(0)
print(1)
print(2)
print(3)
print(4)

可以通过对树进行预先遍历遍历来跟踪函数调用序列。将对node-value大于0的节点执行print语句,并在该节点的两个子节点都返回后执行。

答案 1 :(得分:0)

我试图通过图表来详细说明。看一看! Lat n = 3; enter image description here