Skip to content

Instantly share code, notes, and snippets.

@akshayas
Created July 12, 2012 06:02
Show Gist options
  • Save akshayas/3096189 to your computer and use it in GitHub Desktop.
Save akshayas/3096189 to your computer and use it in GitHub Desktop.
Number of binary trees possible with n nodes
/**
* Write code to compute number of structural different
* binary trees for given 'n' number of nodes.
* (with and without Catalan number)
*/
package problems;
public class noOfBinaryTrees {
public static int noOfTrees(int totalNodes) {
if(totalNodes <= 1)
return 1;
int sum = 0;
for(int i = 1; i <= totalNodes; i++) {
int leftTree = noOfTrees(i - 1);
int rightTree = noOfTrees(totalNodes - i);
sum += (leftTree * rightTree);
}
return sum;
}
// Main to test the code. Better to write JUnit code
public static void main(String[] args) {
System.out.println(noOfTrees(3));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment