1047. Understand Recursion by Printing
You're given an integer n. Your task is to implement a recursive function that helps you understand recursion by printing messages before and after the recursive call.
Write a function understandRecursion(int n) that prints the following:
- Print "Entering recursion with n = X" before the recursive call
- Print "Exiting recursion with n = X" after the recursive call
The recursion should terminate when n becomes 0.
Example 1:
Input: n = 2
Output:Ā
Entering recursion with n = 2
Entering recursion with n = 1
Entering recursion with n = 0
Exiting recursion with n = 0
Exiting recursion with n = 1
Exiting recursion with n = 2
Explanation: The function recurses from n = 2 to n = 0, then prints on the way back.
Example 2:
Input: n = 0
Output:Ā
Entering recursion with n = 0
Exiting recursion with n = 0
Explanation: Since n is already 0, only one pair of messages is printed.
Still unsure what the problem is asking ?
Letās go through a few more examples, step by step, to make it clearer.
Example 3:
Input: n = 3
Output:Ā
Entering recursion with n = 3
Entering recursion with n = 2
Entering recursion with n = 1
Entering recursion with n = 0
Exiting recursion with n = 0
Exiting recursion with n = 1
Exiting recursion with n = 2
Exiting recursion with n = 3
Explanation: Recursion goes down from 3 to 0 and then exits in reverse order.
Constraints:
- 0 <= n <= 10