- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have n different nodes. All are distinct. We have to find how many number of ways we can arrange them to form Binary search tree. As we know for binary search trees, the left subtree always hold smaller values and right subtrees hold the greater values.

To solve this, we shall find the Catalan number. The Catalan number C(n) represents the binary search trees with n different keys. The formula is like

$$C(n)=\frac{(2n)!}{(n+1)!\times n!}$$

So, if the input is like n = 3, then the output will be 5 because

To solve this, we will follow these steps −

- Define a function ncr() . This will take n, r
- res := 1
- if r > n - r, then
- r := n - r

- for i in range 0 to r - 1, do
- res := res *(n - i)
- res := floor of (res/(i + 1))

- return res
- From the main method, do the following
- c := ncr(2 * n, n)
- return floor of c /(n + 1)

Let us see the following implementation to get better understanding −

from math import factorial def ncr(n, r): res = 1 if r > n - r: r = n - r for i in range(r): res *= (n - i) res //= (i + 1) return res def solve(n): c = ncr(2 * n, n) return c // (n + 1) n = 3 print(solve(n))

3

5

- Related Questions & Answers
- Python program to create a doubly linked list of n nodes and count the number of nodes
- Python program to create a Circular Linked List of N nodes and count the number of nodes
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- Program to count number of stepping numbers of n digits in python
- Golang Program to count the number of nodes in a linked list.
- Count BST nodes that lie in a given range in C++
- Program to count number of ways we can throw n dices in Python
- Program to count number of on lights flipped by n people in Python
- Program to count the number of ways to distribute n number of candies in k number of bags in Python
- Program to find number of possible BSTs can be generated using n distinct nodes in Python
- Program to find higher number with same number of set bits as n in Python?\n
- Write a program in Python to count the number of digits in a given number N
- Program to remove all nodes from BST which are not in range in Python
- Program to make almost BST to exact BST in python
- Golang program to count the number of nodes in a doubly linked list.

Advertisements