
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count number of BST with n nodes in Python
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)
Example
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))
Input
3
Output
5
- Related Articles
- Python program to create a Circular Linked List of N nodes and count the number of nodes
- Python program to create a doubly linked list of n nodes and count the number of nodes
- Python Program to Count Number of Non Leaf Nodes of a given Tree
- Golang Program to Count number of leaf nodes in a tree
- Program to count number of stepping numbers of n digits in python
- Program to remove all nodes from BST which are not in range in Python
- Count BST nodes that lie in a given range in C++
- Golang Program to count the number of nodes in a linked list.
- Golang program to count the number of nodes in a doubly linked list.
- 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 find number of possible BSTs can be generated using n distinct nodes in Python
- Program to make almost BST to exact BST in python
- Write a program in Python to count the number of digits in a given number N
- Program to count the number of ways to distribute n number of candies in k number of bags in Python

Advertisements