Given N, Find the total number of unique BSTs that can be made using values from 1 to N.
Input: n = 3 Output: 5 For n = 3, preorder traversal of Unique BSTs are: 1. 1 2 3 2. 1 3 2 3. 2 1 3 4. 3 1 2 5. 3 2 1 Input: 4 Output: 14
In the previous post a O(n) solution has been discussed. In this post we will discuss a solution based on Dynamic Programming. For all possible values of i, consider i as root, then [1….i-1] numbers will fall in the left subtree and [i+1….n] numbers will fall in the right subtree. So, add (i-1)*(n-i) to the answer. The summation of the products will be the answer to the number of unique BST.
Below is the implementation for above approach:
Number of structurally Unique BST with 3 keys are : 5
Time Complexity: O(n2)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Improved By : shiv_bhakt
- Total number of possible Binary Search Trees and Binary Trees with n keys
- Water Jug Problem using Memoization
- Longest Increasing Subsequence | DP-3
- Dynamic Programming vs Divide-and-Conquer
- Paytm Interview experience for FTE (On-Campus)
- Balanced expressions such that given positions have opening brackets | Set 2
- Number of ways a convex polygon of n+2 sides can split into triangles by connecting vertices
- Alternate Fibonacci Numbers
- Find the largest area rectangular sub-matrix whose sum is equal to k
- Sum of elements of all partitions of number such that no element is less than K