Sunday, April 18, 2010

Counting the number of ways BST can be formed

The problem is posed as follows: Given numbers from 1 to n, In how many ways can you form a BST. For example if number given is 1 to 3. How many ways can we proceed? We can break this down to problem where we count number of possibilities when root is 1,2 and 3 respectively. And then we sum all those values to give total number of possibilities. Now when 1 is root, we can proceed to count possibilities when 2 is the root for the right subtree of 1 and when 3 is the root of the right subtree of 1. This gives us the fair idea that we can proceed recursively and count the possibilities. For left and right subtrees we multiply each other to give total number of possibilities. This translates into simple code given below:

  
//compute how many BST can be formed for given number of inorder, no duplicates
int comb_count(int begin, int end) {

if(begin >= end)
return 1;
int count = 0;
for(int i = begin ; i <= end; i++) {
//take this as root and find how the
//nodes can be arranged on the left or right
count+= comb_count(begin, i - 1) * comb_count(i + 1, end);
}
return count;
}

No comments:

Post a Comment