algorithmrecursionbinary-treecatalan

Recurrence Relation: Writing a recurrence relation


I'm trying to write a recurrence relation for this algorithm.But I've got confused with the "root" variable.Can anyone help me or suggest me a better recursive algorithm to count the number of possible binary trees with n nodes?

Algorithm countTrees(n) {
    if(n<=1) then return 1
    else {
        sum = 0
        for root=1 to root<= n do {
            left = countTrees(root-1)
            right = countTrees(n-root)
            sum = sum+(left*right)
        }
        return sum
    }
}

I've written this so far but I don't know how to deal with the root to solve this.

T(n) = n[T(root-1)+T(n-root)]


Solution

  • Your code is already a recurrence relation for the number of binary trees, just expressed as an algorithm. I guess you were stuck because you had a summation over a loop. Here it is in standard mathematical notation-- with the loop value changed from 1..n to 0..n-1 to be more standard:

    C(0) = C(1) = 1
    C(n) = sum(C(i) * C(n-i-1) for i = 0...n-1)
    

    Writing it by hand (or with LaTeX) you'd use a summation sign rather than sum, but it's logically the same.

    This is the recurrence relation for the Catalan numbers (although normally the C(1) case would not be explicitly listed) and the Wikipedia page linked also includes the closed-form solution for the recurrence relation and proofs of its correctness.