Created
July 12, 2012 06:02
-
-
Save akshayas/3096189 to your computer and use it in GitHub Desktop.
Number of binary trees possible with n nodes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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