Home » Program to Find the Total Number of Possible Binary Search Trees with N Keys

Program to Find the Total Number of Possible Binary Search Trees with N Keys

by Online Tutorials Library

Q. Program to find the total number of possible Binary Search Trees with n keys.

Explanation

In this program, we need to find out the total number of binary search trees can be constructed with n values. Below diagram shows a possible binary search tree with the key value as 3. So, we can construct a total of five binary search trees. When we choose node 1 as the root node, we get two trees. Similarly, one tree with 2 as root node and two trees when we select 3 as the root node.

This approach involves selecting a node recursively as the root node and create possible binary search tree.

An easy way to calculate the total number of possible binary search trees are through Catalan number:

Program to find the total number of possible Binary Search Trees with n keys

Algorithm

  1. Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  2. When a node is created, data will be passed to the data attribute of the node and both left and right will be set to null.
  3. Define another class which has an attribute root.
    1. Root represents the root node of the tree and initialize it to null.
  4. numOfBST() will find out total possible binary search tree for given key:
    1. It will calculate the Catalan number for given key by making a call to factorial().
    2. Catalan number can be calculated using the formula:
      Cn = (2n)! / n! *(n+1)!
    3. Factorial() will calculate factorial of a given number.

Solution

Python

Output:

Total number of possible Binary Search Trees with given key: 42  

C

Output:

Total number of possible Binary Search Trees with given key: 42  

JAVA

Output:

Total number of possible Binary Search Trees with given key: 42  

C#

Output:

Total number of possible Binary Search Trees with given key: 42  

PHP

Output:

Total number of possible Binary Search Trees with given key: 42  

Next TopicPrograms List

You may also like