Total number of possible Binary Search Trees and Binary Trees with n keys | See https : www . geeksforgeeks . org / program - nth - catalan - number / for reference of below code . ; A function to find factorial of a given number ; Calculate value of [ 1 * ( 2 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; A function to count number of BST with n nodes using catalan ; find nth catalan number ; return nth catalan number ; A function to count number of binary trees with n nodes ; find count of BST with n numbers ; return count * n ! ; Driver Code ; find count of BST and binary trees with n nodes ; print count of BST and binary trees with n nodes
import java . io . * ; class GFG { static int factorial ( int n ) { int res = 1 ; for ( int i = 1 ; i <= n ; ++ i ) { res *= i ; } return res ; } static int binomialCoeff ( int n , int k ) { int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } static int catalan ( int n ) { int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } static int countBST ( int n ) { int count = catalan ( n ) ; return count ; } static int countBT ( int n ) { int count = catalan ( n ) ; return count * factorial ( n ) ; } public static void main ( String [ ] args ) { int count1 , count2 , n = 5 ; count1 = countBST ( n ) ; count2 = countBT ( n ) ; System . out . println ( " Count ▁ of ▁ BST ▁ with ▁ " + n + " ▁ nodes ▁ is ▁ " + count1 ) ; System . out . println ( " Count ▁ of ▁ binary ▁ " + " trees ▁ with ▁ " + n + " ▁ nodes ▁ is ▁ " + count2 ) ; } }