Recursion output

元气小坏坏 提交于 2021-02-16 20:33:49

问题


I was just introduced to recursion and I was given the following lines of code:

public class RecursionThree
{
   public void run(int x )
   {
      if(x<5)
         run(x+1);
      out.println(x);
   }
   public static void main(String args[]  )
   {
      RecursionThree test = new RecursionThree ();
      test.run(1);
   }
}

and the output is supposed to be: 5 4 3 2 1. I get why it would print 5 (because 5<5 would equal false and it would print x, which is 5). However, I do not understand why it prints 4 3 2 1 too. Thanks for your help


回答1:


How recursion works is you break down to the base case and build up backwards. In your case. Your base case was x>=5, the point at which it would stop expanding the recursive tree, you can think of the base case as the end of the tree, or leaf. After that it goes back up completing things that were to be done after run was called. SO in your case, each time after calling one, it printed out x.

When x=1, it calls run(2), after run(2) is resolved, it would go to the next line. After run(2), the print out is 5 4 3 2 after that it would print out x coming back to the original call of run(1), which would be 1. This is really great for traversing trees etc and a lot of other problems.

To picture it, when you call run(1)

run(1)
 1<5
  run(2)
   2<5
    run(3)
     3<5
      run(4)
       4<5
        run(5)
          print(5)
       print(4)
     print(3)
   print(2)
 print(1)

As you can see it goes to the base case, and back up.

To get familiar with recursion more, you can do problems like, finding the largest int in an array with the method head being public int findLargest(int [] array, int someNumber) where you would use someNumber to whatever you think you need. Or reversing a string using recursion and one parameter.




回答2:


For your x=4 case, run(5) was called. After that completed running, control was returned to the callee function, where x is presently 4. So, it executes the line after the if which prints the 4.

The same logic follows for x = 3, 2, 1.



来源:https://stackoverflow.com/questions/35834665/recursion-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!