3

Let's represent the tree via list.

If the number of the leafs is two, A and B. Then there is only one tree (A B).

If the number of the leafs is three, A, B and C. Then there are two trees ((A B) C) and (A (B C)).

So if there are N leafs, how many trees are there?

Guy Coder
  • 24,501
  • 8
  • 71
  • 136
louxiu
  • 2,830
  • 3
  • 28
  • 42
  • ***"Let's represent the tree via list."*** Clarify please how you do that? – ypercubeᵀᴹ Dec 31 '12 at 14:18
  • Here is a hint: if the number of leaves is a power of 2, then there is one binary tree with the leaves in the specified order. – gogognome Dec 31 '12 at 14:28
  • @gogognome I don't think that's true. For example, check this:http://draw.to/DfUt2p. It shows an 8-leaf binary tree which isn't balanced. – Omri Barel Dec 31 '12 at 16:14
  • @louxiu is there any restriction on the degree of internal nodes? For example, if you allow degree = 1 then there is an infinite number of binary trees with N nodes in the given order. Also, is there any restriction on total number of nodes? – Omri Barel Dec 31 '12 at 16:17
  • Indeed @OmriBarel, you are right. I assumed the binary tree was balanced and the and that the non-leaf-nodes have two child nodes. – gogognome Dec 31 '12 at 18:10

1 Answers1

6

Let the number of binary trees with N leaves be T(N).

We have T(1) = T(2) = 1, as can be immediately seen, and for N > 2 we can split at the root, obtaining two subtrees with fewer leaves. Or, equivalently, we can assemble a binary tree with N leaves from two non-empty binary trees with k and N-k leaves respectively. The condition that both subtrees are non-empty translates to 1 <= k <= N-1. So we have the recursion

      N-1
T(N) = ∑  T(k) * T(N-k)
      k=1

If the recursion is not yet known, it is not difficult to compute the first few values

1,1,2,5,14,42,132,429,1430,4862,16796

and google them. One finds that these are the Catalan numbers,

C(n) = (2*n)! / (n! * (n+1)!)

offset by one, so

T(N) = C(N-1)

which can be computed much faster than the recursion.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • 1
    +1, nice explanation. And I like catalan numbers! So many things are reduced into them – amit Dec 31 '12 at 16:52
  • Note that there is a condition here on the degree of internal nodes. If for some subtree the root is of degree 1 then you can't split the subtree into two non-empty sub-subtrees. – Omri Barel Dec 31 '12 at 17:07
  • @OmriBarel Of course every non-leaf must have two children, otherwise you'd have ℵ_0 trees for all `N > 0`. – Daniel Fischer Dec 31 '12 at 17:17