-1

I know total number of distinct BST's possible with N distinct nodes are given by Catalan formula . Which is described in this question at SO.

But how can we use it to find all the BSTs less then or equal to n nodes(N distinct nodes)?

for e.g.

For N=3

 Possible numbers of BST's are 14.

 9 Shown in Picture below for less than 3.
 5 for N=3 which can be obtained from Catalan formula.

BST FOR N 3

What is the approach to solve it? I need only algorithmic explanation.

Community
  • 1
  • 1
  • 1
    that will not be correct. `catalanFormula(1)=1,catalanFormula(2)=2,catalanFormula(3)=5` sum of which gives 8 for 3. But answer is 14. – user3594106 Jun 04 '14 at 18:09
  • Its a live contest answers. why are u in such hurry for answers. Answers are anyway published after contests – coder hacker Jun 05 '14 at 03:55

1 Answers1

0

The mathematical formula shall be:

summation ( C(n,i) * Catalan(i) ) {i = 1 to n}

Where C(n,i) = n! / ( i! * (n-i)! )

You can choose i nodes out of a possible n nodes in C(n,i) ways. After choosing those i nodes, form the BSTs in Catalan(i) number of ways.

Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46