
- 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 unique binary search tree can be formed with 0 to n values in Python
Suppose we have one number n, we have to find the number of unique BSTs we can generate with numbers from [0, n). If the answer is very large mod the result by 10^9+7
So, if the input is like n = 3, then the output will be 5
To solve this, we will follow these steps −
- numer := 1
- denom := n + 1
- for i in range 1 to n, do
- numer := numer * n + i
- numer := numer mod m
- denom := denom * i
- denom := denom mod m
- numer := numer * (denom^(m-2)) mod m
- return numer mod m
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, n): m = 10 ** 9 + 7 numer = 1 denom = n + 1 for i in range(1, n + 1): numer *= n + i numer %= m denom *= i denom %= m numer *= pow(denom, m-2, m) return numer % m ob = Solution() print(ob.solve(4))
Input
4
Output
14
- Related Articles
- Python Program to Sort using a Binary Search Tree
- Program to create linked list to binary search tree in Python
- Count of alphabets whose ASCII values can be formed with the digits of N in C++
- Count the Number of Binary Search Trees present in a Binary Tree in C++
- C++ Program to count number of teams can be formed for coding challenge
- Program to count number of sublists with exactly k unique elements in Python
- Program to count number of BST with n nodes in Python
- Binary Tree to Binary Search Tree Conversion in C++
- Program to count number of palindromes of size k can be formed from the given string characters in Python
- Program to count number of unique palindromes we can make using string characters in Python
- C++ Program to Implement Randomized Binary Search Tree
- Python Program to Implement Binary Search with Recursion
- Convert Sorted Array to Binary Search Tree in Python
- Validate Binary Search Tree in Python
- Program to count number of ways we can throw n dices in Python

Advertisements