跟踪递归函数

Aub*_*rey 0 java recursion function

对于以下代码段,我无法通过它进行跟踪(我需要能够为即将进行的测试执行此操作.

public int question(int x, int y)
{
    if (x ==y)
        return 0;
    else
        return question(x-1, y) + 1;
}
Run Code Online (Sandbox Code Playgroud)

我也很担心+ 1正在做什么.什么是1被添加到.我知道结果是五,但我需要能够更好地理解这个概念.谢谢你的帮助.

M. *_*haw 5

基本上:

question(8,3) 将返回 question(7,3) + 1

question(7,3) 将返回 question(6,3) + 1

question(6,3) 将返回 question(5,3) + 1

question(5,3) 将返回 question(4,3) + 1

question(4,3) 将返回 question(3,3) + 1

并且question(3,3)是0.

很明显,question(8,3)简单替换的结果是5.应该注意的是,如果x < y那时你可能会得到一个堆栈溢出,因为它x会不断递减,并且可能永远不会到达x == y.