【发布时间】:2015-08-08 08:19:02
【问题描述】:
我有 n 个元素,例如 1,2,3,4....n。我想计算所有可能根的高度为 H 的可能二叉搜索树的数量
计算所有可能高度的二叉搜索树的数量:
int countTrees(int N) {
if (N <=1) {
return(1);
}
else {
int sum = 0;
int left, right, root;
for (root=1; root<=N; root++) {
left = countTrees(root - 1);
right = countTrees(N - root);
// number of possible trees with this root == left*right
sum += left*right;
}
return(sum);
}
}
在上面的程序中,我想添加高度H的约束
编辑: 示例 -
Input N = 3 H = 3
我不想计算高度大于 H 的树
Total No. of tree 5
There are 2 trees with root =1, 1 tree with root =2, 2 trees with root =3
我的最终答案是 10(所有根节点数的总和)因此, 答案 = 1*2 + 2*1 + 3*2 = 10
【问题讨论】:
-
您能否举个例子详细说明。
-
错误?
sum += root*left*right;-->sum += left*right; -
@Antonio 你不认为提供的示例是错误的,因为输出应该是 4。
-
例子是错误的,没有约束,输出为5,加上约束后,输出只会减少。
-
@SaketMittal 请查看我的更新代码。
标签: java c++ algorithm tree binary-search-tree