Ninja and Bob were playing the game. Ninja challenged Bob to solve the following problem.
Given an integer 'N' Bob has to find the total number of different binary search trees that can be formed with 'N' different nodes.
Your task is to help Bob to solve the task given by Ninja to him.
Print the answer modulo 1000000007.
Example:Input: ‘N’ = 2
Output: 2
Explanation: We can form two different BSTs with two nodes only.
One with node one as a root and the other with node two as a root.
The first line of input contains an integer ‘T', denoting the number of test cases.
Each test case contains a single integer 'N' denoting the number of nodes.
Output format :
For each test case, print the total number of different binary search trees that can be formed.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
1 <= 'N' <= 10^2
Timit Limit: 1 sec
2
1
2
1
2
With one node, only one possible BST can be formed.
With the two nodes, we can form two different BSTs. One with the first node as a root and the other with the second node as a root.
2
3
4
5
14
Try to think about in the recursive manner.
Approach: We will start by taking any of the node 1...n as the root node. Let the chosen root node be i. Then, we have a BST where the root node is i; the left child consists of all nodes from 1...i-1 (since the left sub-tree must have only less than root value), and the right child consists of all nodes from i+1...n. We will recursively call it for all possible cases and count the number of BSTs.
Algorithm :
O(3^N), where 'N' is the number of nodes in the BST.
Asymptotically we will require to call the recursion 3^N times. Hence the time complexity will be O(3^N).
O(N), where 'N' is the number of nodes in the BST.
Because of the space used by the function call stack during recursive function calls, the overall space complexity will be O(N).