我有一个问题,我不确定如何开始。有人可以解释如何做这个递归树吗?无论如何要在Java上做到这一点吗?
对于下面定义的递归方法fnc(n,k),绘制调用fnc(3,5)的递归树。
您的图表应包含所有方法调用的返回值
fnc(n,k)
。
public static int fnc(int n, int k) {
if ( (n <= 1) || (k <= 1) ) {
return n+k; } else {
return fnc(n-1,k) + fnc(n,k-2);
}
}
答案 0 :(得分:0)
如果我理解正确,你只需要跟踪递归的级别并使用它来控制缩进...
实施例
static int fnc(int n, int k, int level) {
System.out.println(String.format("%sfnc(%d, %d)", pad(level), n, k));
int result;
if ((n <= 1) || (k <= 1)) {
result = n + k;
} else {
result = fnc(n - 1, k, level + 1) + fnc(n, k - 2, level + 1);
}
System.out.println(String.format("%s<== %d", pad(level), result));
return result;
}
private static String pad(int level) {
String pad = "";
for (int i = 0; i < level; i++) {
pad += " ";
}
return pad;
}
public static void main(String[] args) {
fnc(3, 5, 0);
}
输出
fnc(3, 5)
fnc(2, 5)
fnc(1, 5)
<== 6
fnc(2, 3)
fnc(1, 3)
<== 4
fnc(2, 1)
<== 3
<== 7
<== 13
fnc(3, 3)
fnc(2, 3)
fnc(1, 3)
<== 4
fnc(2, 1)
<== 3
<== 7
fnc(3, 1)
<== 4
<== 11
<== 24