用java代码实现最优二叉搜索树的简单递归算法,输出最优平均查找次数
时间: 2023-06-10 15:03:45 浏览: 100
好的,以下是用java代码实现最优二叉搜索树的简单递归算法,并输出最优平均查找次数的示例代码:
```
public class OptimalBST {
public static int optimalBST(int[] keys, int[] freq) {
int n = keys.length;
int[][] dp = new int[n + 1][n + 1];
for (int i = 0; i < n; i++) {
dp[i][i] = freq[i];
}
for (int len = 2; len <= n; len++) {
for (int i = 0; i <= n - len + 1; i++) {
int j = i + len - 1;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k <= j; k++) {
int temp = ((k > i) ? dp[i][k - 1] : 0) +
((k < j) ? dp[k + 1][j] : 0) + sum(freq, i, j);
if (temp < dp[i][j]) {
dp[i][j] = temp;
}
}
}
}
return dp[0][n - 1];
}
private static int sum(int[] freq, int i, int j) {
int sum = 0;
for (int x = i; x <= j; x++) {
sum += freq[x];
}
return sum;
}
public static void main(String[] args) {
int[] keys = {10, 12, 20};
int[] freq = {34, 8, 50};
int result = optimalBST(keys, freq);
System.out.println("最优平均查找次数为:" + result);
}
}
```
注:此代码参考了我们的CSDN博主所写的文章,不过具体地址已经无从考起,如有雷同请见谅!
阅读全文