Skip to content

Commit 1412efa

Browse files
committed
tree-2
1 parent d0d7488 commit 1412efa

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/main/java/com/chen/algorithm/znn/tree/test111/Solution.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public class Solution {
1515

1616
/**
1717
* 1-深度优先搜索(DFS),即递归
18-
*
18+
* 叶子结点都为空,需要走到叶子结点,当一个结点为空一个结点不为空时,说明叶子结点在不为空的那个节点,返回不为空
1919
* @param root
2020
* @return
2121
*/
@@ -35,9 +35,15 @@ public int minDepth1(TreeNode root) {
3535
return 0;
3636
}
3737

38+
//if(root.left == null && root.right == null){
39+
// return 1;
40+
//}
41+
3842
int leftDepth = minDepth1(root.left);
3943
int rightDepth = minDepth1(root.right);
4044

45+
// 叶子结点,是左右子节点都为空的节点,当某一个子节点为空时,则返回另一个结点的高度。
46+
// 当一个结点为空一个结点不为空时,说明**叶子结点**在不为空的那个节点。
4147
return root.left == null || root.right == null ? leftDepth + rightDepth + 1 : Math.min(leftDepth, rightDepth) + 1;
4248
}
4349

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,37 @@
11
package com.chen.algorithm.znn.tree.test96;
22

3+
import org.junit.Test;
4+
35
/**
46
* @Auther: zhunn
57
* @Date: 2020/10/29 17:49
6-
* @Description: 不同的二叉搜索树:动态规划
8+
* @Description: 不同的二叉搜索树:1-动态规划
79
*/
810
public class Solution {
911

12+
/**
13+
* 1-动态规划 求G(n)
14+
* G(0) = 1,G(1) = 1
15+
* G(n) = G(i-1)*G(n-i) 求和(1<= i <=n)
16+
*
17+
* @param n
18+
* @return
19+
*/
20+
public int numTrees(int n) {
21+
int[] dp = new int[n + 1];
22+
dp[0] = 1;
23+
dp[1] = 1;
24+
25+
for (int i = 2; i <= n; i++) {
26+
for (int j = 1; j <= i; j++) {
27+
dp[i] += dp[j - 1] * dp[i - j];
28+
}
29+
}
30+
return dp[n];
31+
}
32+
33+
@Test
34+
public void test() {
35+
System.out.println(numTrees(3));
36+
}
1037
}

0 commit comments

Comments
 (0)