-1
$\begingroup$
class test{
  public static void main(String args[]){
  int n = 5;
  mystery(n);
}

  public static void mystery(int n)
{

  if(n == 0 || n==1)
  {
   return;
  }
  mystery(n-2);
  System.out.println(n);
  mystery(n-1);
  }
}

This a very simple void method code.

I want to know what happen during the recursion and why is the output is like that??

the output to the console is:

3

2

5

2

4

3

2

$\endgroup$

closed as off-topic by David Richerby, jmite, D.W. Apr 13 '17 at 23:34

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – David Richerby, jmite, D.W.
If this question can be reworded to fit the rules in the help center, please edit the question.

1
$\begingroup$

Consider the following binary tree mystery-tree(5)

         5
        / \
       /   \
      /     \
     4       3
    / \     /
   /   \   /
  3     2 2
 / 
2

Clearly mystery-tree(5) is defined by:

mystery-tree(1) = null
mystery-tree(2) = null
mystery-tree(n) = Node n mystery-tree(n - 1) mystery-tree(n - 2)

Clearly the output you showed is just the reversed in-order traversal of this tree, i.e. mystery(n) = for i in reversed(in-order(mystery-tree(n))) { println(n) }.

$\endgroup$
  • $\begingroup$ How does that answer the question? $\endgroup$ – Yuval Filmus Apr 14 '17 at 0:07
  • $\begingroup$ The hope is that decomposing the function makes it less of a mystery. This directly addresses the second question. $\endgroup$ – walpen Apr 14 '17 at 0:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.