Skip to content

Commit 8f28a48

Browse files
committed
tree
1 parent 3292319 commit 8f28a48

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

tree/NumTrees.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package Algorithms.tree;
22

33
public class NumTrees {
4-
public int numTrees(int n) {
4+
public int numTrees1(int n) {
55
// cnt[n] = cnt[0]cnt[n - 1] + cnt[1]cnt[n - 2] ... cnt[n - 1]cnt[0]
66
// cnt[n-1] = cnt[0]cnt[n - 2] + cnt[1]cnt[n - 3] ... cnt[n - 2]cnt[0]
77
// For example:
@@ -26,4 +26,19 @@ public int numTrees(int n) {
2626

2727
return cnt[n];
2828
}
29-
}
29+
30+
public int numTrees(int n) {
31+
if (n == 0) {
32+
return 1;
33+
}
34+
35+
// Get the results of all the trees which
36+
// has the root from 1 to n;
37+
int num = 0;
38+
for (int i = 0; i <= n - 1; i++) {
39+
num += numTrees(i) * numTrees(n - 1 - i);
40+
}
41+
42+
return num;
43+
}
44+
}

0 commit comments

Comments
 (0)