# How does recursion work in void method java [closed]

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

## 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.

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) }.

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