递归深度 – Java中的制表符和凹痕

我想格式化我的Java程序输出,以便我可以看到递归的“有多深”。 怎么做? 重要的是不要迷失在我的递归树中。

示例输出(用于从0开始计算第n个数字的普通递归函数):

This is the first recursive call. Input value: 3. This is the second recursive call. Input value: 2. This is the 3rd recursive call. Input value: 1. Output value : 1. This is again the second recursive call. Input value: 2. Output value : 1 + 1. This is again the first recursive call. Input value: 3. Output value : 1 + 1 + 1. 

您可以使用表示您有多深的变量(如level )。 它从1开始,并在每次递归调用时递增。

 public static void main(String[] args) { function(3, 1); } public static String function(int input, int level) { String tab = ""; for (int i = 0; i < level - 1; i++) { tab += "\t"; } System.out.println(tab + "This is the " + level + " recursive call. Input value: " + input); if (input == 1) { System.out.println(tab + "Output value: 1"); return "1"; } String output = function(input - 1, level + 1); System.out.println(tab + "This is again the " + level + " recursive call. Input value: " + input); System.out.println(tab + "Output value: " + output + " + 1"); return output + " + 1"; } 

好吧,如果您正在使用System.out.println,那么您应该能够使用“\ t这是……”来缩进大多数Java输出窗口中的行。 我不明白这是不是你要求的。

如果你不知道你所在的递归,那么你必须抓取Thread.currentThread()。getStackTrace()。

 String s = ""; while(numRecursions --> 0) s += "\t"; System.out.println(s + "Something something something") 

同样,如果你没有numRecursions变量,那么你必须做这样的事情

  int numRecursions = 0; void a(){ int temp = ++ numRecursions; String s = ""; while(temp --> 0) s += "\t"; System.out.println(s + "This is a recursion level"); //code numRecursions--; } 

在您的输出函数中包含前缀字符串参数。
每次调用函数时都会传递前缀+“”。 例:

 public void output(String prefix){ // Whenever you print, start with prefix System.out.println(prefix + ...); // When you call your recursive method String childPrefix = prefix+" "; output(childPrefix); }