How many binary search trees can be constructed from n distinct elements? And how can we find a mathematically proved formula for it?
Example: If we have 3 distinct elements, say 1, 2, 3, there are 5 binary search trees.
Given n elements, the number of binary search trees that can be made from those elements is given by the nth Catalan number (denoted Cn). This is equal to
Intuitively, the Catalan numbers represent the number of ways that you can create a structure out of n elements that is made in the following way:
This pattern perfectly matches the ways in which you can build a BST from a set of n elements. Pick one element to use as the root of the tree. All smaller elements must go to the left, and all larger elements must go to the right. From there, you can then build smaller BSTs out of the elements to the left and the right, then fuse them together with the root node to form an overall BST. The number of ways you can do this with n elements is given by Cn, and therefore the number of possible BSTs is given by the nth Catalan number.
Hope this helps!
I am sure this question is not just to count using a mathematical formula.. I took out some time and wrote the program and the explanation or idea behind the calculation for the same.
I tried solving it with recursion and dynamic programming both. Hope this helps.
The formula is already present in the previous answer:
So if you are interested in learning the solution and understanding the apporach you can always check my article Count Binary Search Trees created from N unique elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With