For example for N=3, we can find easily by listing them all, but when asked for any arbitrary N value I am facing problem.

- 24,501
- 8
- 71
- 136

- 711
- 1
- 10
- 31
-
5This question appears to be off-topic because it is about math. Consider posting it to math.stackexchange.com. – Sergey Kalinichenko Aug 09 '13 at 18:59
-
1http://en.wikipedia.org/wiki/Permutation – gtgaxiola Aug 09 '13 at 18:59
-
What would be your answer for N=3? 5 or 12? Could you specify what kind of trees do you mean? Binary trees, or arbitrary. – Thomas B. Aug 09 '13 at 19:36
-
1https://en.wikipedia.org/wiki/Catalan_number – starblue Aug 09 '13 at 20:35
-
for example three nodes are a,b,c; abc, cba, bac, cab, acb, bca; where middle element is root and left and right elements are its left and right nodes. – abhilash_goyal Aug 10 '13 at 12:59
4 Answers
If you are looking at binary trees then, as mcdowella said, Choose(2n,n)/(n+1) (Catalan number) is the answer.
If you are looking at arbitrary trees then it is probably n. n^(n-2) = n^(n-1), but I am not totally sure. Prufer's algo tells us that there are n^(n-2) labeled trees and any of the nodes can be made a root, thus we get the number n^(n-1).

- 46
- 4
This is covered in Knuth Vol 1 (The Art of Computer Programming: Fundamental Algorithms) section 2.3.4.4 About half a page of maths gives you Choose(2n, n) / (n + 1) and searching for the sequence in Knuth finds http://oeis.org/A000108

- 19,301
- 2
- 19
- 25
You could go about it like this using dynamic programming :
Let's fix element i as the root
of the tree. Now we need to know how many different trees
we can form with the first (i-1) elements and the rest (n-i-1) elements
.
So we follow the same procedure for these two subarrays (i-1)
and (n-i-1)
to obtain the following recurrence:
Formula:
LaTeX:
Trees[n]&space;=&space;\sum_{i&space;=&space;2}^{i&space;=&space;n-1}&space;Trees[i-1]*Trees[n-i-1]

- 895
- 1
- 8
- 22

- 332
- 1
- 5
- 13
Binary Trees (2n,n)/(n+1) (Catalan number) as the answer If labeled trees than n^(n-2) trees .