递归 - 为什么使用return语句

swa*_*ati 8 java recursion

我正在学习递归,下面是我要追踪的一个例子,以便更好地理解它

public static void main(String []args) {
    new TestRecursion().strRecur("abc");
}

public void strRecur(String s) {
    if(s.length() < 6) {
        System.out.println(s);
        strRecur(s+"*");
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我到目前为止所理解的内容.- 在第一次调用时strRecur("abc"),该方法被添加到执行堆栈中.由于使用参数"abc*"进行递归调用,它会在暂停之前打印"abc".

  • 第二次使用"abc*"调用,将方法推strRecur(abc*)送到堆栈并将"abc*"打印到控制台.

  • 第三次使用"abc**"调用,将方法推strRecur(abc**)送到堆栈并将"abc**"打印到控制台.

  • 第四次调用"abc***",将方法推strRecur(abc***)送到堆栈.由于满足基本条件,该方法完成(不打印任何内容)并弹出堆栈.

  • 第三次调用"abc**"已完成并弹出.由于没有待执行的代码可以执行任何操作.

  • 第二次调用"abc*"已完成并弹出.由于没有待执行的代码可以执行任何操作.

  • "abc"的初始调用已完成并弹出.由于没有待执行的代码可以执行任何操作.

堆

打印到控制台后面 -

abc
abc*
abc**
Run Code Online (Sandbox Code Playgroud)

我想我明白这里发生了什么.现在,我想尝试稍微改变一下这段代码.strRecur(s+"*")我想做而不是打电话return strRecur(s+"*")

public class TestRecursion {

    public static void main(String []args) {
        new TestRecursion().strRecur("abc");
    }

    public String strRecur(String s) {
        if(s.length() < 6) {
            System.out.println(s);
            return strRecur(s+"*");
        }
        return "Outside If";
    }
}
Run Code Online (Sandbox Code Playgroud)

我的期望是,一旦strRecur(abc***)弹出,它的输出(abc***)将返回到strRecur()堆栈中的下一个,所以我会在控制台中看到abc****.对于其他递归调用也是如此.

但是,这种情况下的输出与没有return语句时的输出完全相同.我的理解(当然这是不正确的)源于递归因子实现,我们在那里做类似的事情

return n * fact(n-1);
Run Code Online (Sandbox Code Playgroud)

一旦堆栈上的前一个方法完成,就会fact(n-1)使用返回值解析此处n.为什么在此示例中返回的行为方式不同?

Era*_*ran 9

两种方法的输出都是由println递归方法中的语句产生的,这就是为什么它在两种方法中都是相同的.

第二种方法返回的值不会在任何地方打印,这就是您看不到它的原因.

如果要打印第二种方法的结果,您将看到它"Outside If",因为这是最后一次递归调用的输出,然后由所有其他方法调用返回.

如果你想要输出abc***,你应该

return s;
Run Code Online (Sandbox Code Playgroud)

代替

return "Outside If";
Run Code Online (Sandbox Code Playgroud)

完整的代码是:

public static void main(String[] args) {
    System.out.println(new TestRecursion().strRecur("abc"));
}

public String strRecur(String s) {
    if(s.length() < 6) {
        return strRecur(s+"*");
    }
    return s;
}
Run Code Online (Sandbox Code Playgroud)