What does this function do? And how do you evaluate it?
How to trace it? How to understand recursive method?
I just can’t understand the recursion, and the exam date is coming soon, and I know in order to understand recursion, I must first understand recursion.
But I just can’t write a slightly complex recursive method, can anyone help me out using the simplest English words.
public class BalancedStrings {
public static void printBalanced(String prefix, int a, int b) {
if (a > 0)
printBalanced(prefix + "a", a - 1, b);
if (b > 0)
printBalanced(prefix + "b", a, b - 1);
if (a == 0 && b == 0)
System.out.println(prefix);
}
public static void printBalanced(int n) {
if (n % 2 == 0) {
printBalanced("", n / 2, n / 2);
}
}
public static void main(String[] args) {
printBalanced(4);
}
}
The calls to
printBalanced()are the recursive calls. The way to recognize recursion is when a function is calling itself. Recursion is best understood when drawn using a tree:The branches of the tree will continue to create more functions until an end condition is met, which in this case is
a == 0 && b == 0. The function you provided looks like it is printing the string ‘prefix’ concatenated with a specified number of ‘a’ and ‘b’ characters, recursively. When the variablesaandbreach0, the recursion stops and the result is printed usingSystem.out.println(prefix);In the main function you are passing the integer 4 to
printBalanced(int n)which the callsprintBalanced(String prefix, int a, int b)with parameters like this:printBalanced("",2,2);The overall result is prefix concatenated with a balanced number of a’s and b’s