What does this recursive function do?

Posted by null on Stack Overflow See other posts from Stack Overflow or by null
Published on 2012-06-29T15:13:05Z Indexed on 2012/06/29 15:15 UTC
Read the original article Hit count: 157

Filed under:

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

© Stack Overflow or respective owner

Related posts about recursion