Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
class Solution {
public:
int helper(int start, int end){
// not a add up relationship,
// instead it is multiplication relationship.
if (start>=end){
return 1;
}
//else if (start==end)
// return 1;
else{
int total = 0;
for (int i=start;i<=end;i++){
total += helper(start,i-1) *
helper(i+1,end);
}
return total;
}
}
int numTrees(int n) {
return helper(1,n);
}
};
本文详细介绍了如何通过递归方法解决计算给定范围内不同结构的二叉搜索树数量的问题,包括算法实现及具体实例解析。
450

被折叠的 条评论
为什么被折叠?



