Count unique BSTs.

Posted: 3 Dec, 2020
Difficulty: Hard


Try Problem

You have been given a number ‘NUM’. Your task is to count total structurally unique binary search trees from keys 1 to ‘NUM’ considering we should use each key from 1 to ‘NUM’ only once.

Two binary search trees are different if there is at least one node during traversal which is different in values or present in one tree but not present in another tree.

The answer can be large, hence the return answer % ‘MOD’, where ‘MOD’ is a large prime number (10^9 + 7).
Input format :
The first line contains a single integer ‘T’ representing the number of test cases.

The first line of each test case will contain a single integer ‘NUM’ where ‘NUM’ represents the number of keys.
Output Format :
For each test case, print a single line containing the count of total structurally unique binary search trees.

The output of each test case will be printed in a separate line.
You don’t need to print anything; It has already been taken care of. Just implement the given function.
1 <= T <= 100   
1 <= NUM <= 500

Time limit: 1 sec
Approach 1

We can assume a function for calculating the number of ways to calculate the number of trees for the given number of nodes for a fixed root. So we could calculate the number of ways to make a tree as follows. Let’s call the function F(‘X’) giving the number of trees given ‘X’ number of nodes.


We could calculate F(‘X’) = sum of { F(‘i’) * F(‘X’-1-’i’) }. Where i is the assumed number of nodes in the left child of the current root and so the number of remaining nodes for the right child is equal to (‘X’-1-i), hence we could add all these ways multiplicatively, so we could get the total number of ways. 


This value of this function is also defined as Catalan number, which has a specified formula which is equal to ((2*NUM) C (NUM) / (NUM+1)) , but we will calculate the value recursively.


Steps for calculating assuming ‘NUM’ number of nodes in the given tree are as follows: 


  1. If ‘NUM’ is equal to 0 or 1, return the answer as 1, as there is only one tree.
  2. Declare variable ‘SUM’ and initialize it with 0, where sum will store the count of total structurally unique binary search trees.
  3. Run a loop for ‘i’ = ‘0’ to ‘NUM’-1:
    1. ‘SUM’ = ‘SUM’ +  F(‘i’) * F(‘NUM’-1-’i’) to the answer.
  4. Finally, return ‘SUM’ as the answer.
Try Problem