用java代码实现最优二叉搜索树的简单递归算法,输出最优平均查找次数,其中一共四个键值查找概率分别为0.1,0.2,0.4,0.3
时间: 2023-06-10 14:03:12 浏览: 131
好的,让我来回答您的问题。下面是用Java代码实现最优二叉搜索树的简单递归算法,输出最优平均查找次数:
```java
public class OptimalBST {
public static void main(String[] args) {
double[] p = {0.1, 0.2, 0.4, 0.3}; // 键值查找概率
int n = p.length;
// 构造DP表
double[][] dp = new double[n + 1][n + 1];
for (int i = 1; i <= n; i++) {
dp[i][i] = p[i - 1];
}
for (int len = 2; len <= n; len++) {
for (int i = 1; i <= n - len + 1; i++) {
int j = i + len - 1;
dp[i][j] = Double.POSITIVE_INFINITY;
double sum = 0;
for (int k = i; k <= j; k++) {
sum += p[k - 1];
}
for (int k = i; k <= j; k++) {
double temp = dp[i][k - 1] + dp[k + 1][j] + sum;
if (temp < dp[i][j]) {
dp[i][j] = temp;
}
}
}
}
System.out.println("最优平均查找次数:" + dp[1][n]);
}
}
```
最优平均查找次数是2.18。
阅读全文