We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 3292319 commit 8f28a48Copy full SHA for 8f28a48
tree/NumTrees.java
@@ -1,7 +1,7 @@
1
package Algorithms.tree;
2
3
public class NumTrees {
4
- public int numTrees(int n) {
+ public int numTrees1(int n) {
5
// cnt[n] = cnt[0]cnt[n - 1] + cnt[1]cnt[n - 2] ... cnt[n - 1]cnt[0]
6
// cnt[n-1] = cnt[0]cnt[n - 2] + cnt[1]cnt[n - 3] ... cnt[n - 2]cnt[0]
7
// For example:
@@ -26,4 +26,19 @@ public int numTrees(int n) {
26
27
return cnt[n];
28
}
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