Java – how to visualize recursion

I try to understand recursion in Java through visualization I've taken some tutorials on youtube and used one of the examples

public class TestRecursion {

    public static void main(String []args) {
        new TestRecursion().reduceByOne(10);
    }

    public void reduceByOne(int n) {
        System.out.println("Before "+n);
        if(n >= 0) {
            reduceByOne(n-1);
            System.out.println("Inside "+n);
        }
        System.out.println("After "+n);
    }
}

As far as I know, every call to reducebyone () is placed on the execution stack It's like

So first, main () goes to the stack Because it calls reduceByOne (10), this method will go to the stack, then call reduceByOne (9) and push it to the stack and so on. After reducebyone (- 1) is pushed onto the stack, since there are no more methods to execute, reducebyone (- 1) will pop up and execute

I can't understand what happens after the pop-up method? Let's say that reducebyone (2) pops up from the stack I believe that the code to be executed looks like this

public void reduceByOne(2) {
        System.out.println("Before "+2);
        if(2 >= 0) {
            reduceByOne(2-1);
            System.out.println("Inside "+2);
        }
        System.out.println("After "+2);
    }

Won't this put reducebyone (2-1) on the stack again? Or will it be skipped? If so, how does the runtime know what to execute and what to skip once the method pops up?

Maybe I'm too complicated However, I can't understand recursion clearly, so I appreciate any help

Solution

When the method returns (in your case, occurs first when n > = 0), the execution will return to the previous "call" point. In this case, the next line to be executed is system out. println (“Inside”n); After that, each method will continue to exit and return to the previous "call" point in the code

For example

Green is "push" and orange is the result of "popularity"

Obviously, at some point, you will return to the Lord, but this is only an example

This is no different from the way "normal" code works. You call a method and when it returns, it returns to the point where it was executed before

This is an oversimplification of the process, but I hope it allows you to better visualize the process

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>