Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a data structure to store the intermediate sums #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 26 additions & 9 deletions java/src/binarytrees/BstCountTrees.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,35 @@
* For example, countTrees(4) should return 14, since there
* are 14 structurally unique binary search trees that store 1, 2, 3, and 4.
*/
public class BstCountTrees {

public static <T> long countTrees(int numKeys) {
if (numKeys <= 0) {
return 0;
}

public class BstCountTrees
{

private static <T> long countTreesInternal(int numKeys, long[] savedSums)
{

long sum = 0L;
for (int root = 1; root <= numKeys; root++) {
sum += countTrees(root - 1) * countTrees(numKeys - root);
for (int root = 1; root <= numKeys; root++)
{
if (savedSums[root - 1] == 0)
savedSums[root - 1] = countTreesInternal(root - 1,savedSums);
if(savedSums[numKeys - root] == 0)
savedSums[numKeys - root] = countTreesInternal(numKeys - root,savedSums);
sum += savedSums[root - 1] * savedSums[numKeys - root];
}

return sum;
}

public static <T> long countTrees(int numKeys){
long[] savedSums = new long[numKeys + 1];
savedSums[0] = 1;
return countTreesInternal(numKeys, savedSums);
}
public static void main(String[] args)
{
long numTrees = BstCountTrees.countTrees(10);
System.out.println(numTrees);

}

}