96. Unique Binary Search Trees
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?
Example:
Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:
‘
分析:
BST定义:A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the binary search property, which states that the key in each node must be greater than or equal to any key stored in the left sub-tree, and less than or equal to any key stored in the right sub-tree.(WIKI PEDIA)
参考答案解法https://leetcode.com/problems/unique-binary-search-trees/solution/
G(n)是n个数字的BST个数,注意数字是什么对结果没有影响
F(n,i)是n个数字且以第i个数字为根的BST个数。

递推公式:F(i,n)=G(i−1)⋅G(n−i)
那么从前往后可以求出G(n): G(n) = sum(G(i-1)*G(n-i))
public int numTrees(int n) {
if(n==0||n==1)
return 1;
int[] F = new int[n+1];//注意长度
F[0]=1;
F[1]=1;//注意初始化
for(int i=2;i<=n;i++){
for(int j=1;j<=i;j++){
F[i] += F[j-1]*F[i-j];
}
}
return F[n];
}
95. Unique Binary Search Trees II
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
分析:
和上一题区别在于要返回BST的结构而非种类数目。二叉搜索树是有序的,所以以每一个元素为根节点,分别生成左边的元素为其左子树,右边的元素是右子树。
注意:
当节点是null时也要加上,因为null不等于空,也要作为一个元素占List的位子。
还有出现了重复两次结果的问题,是因为我把start=end单独处理了,但是没有立刻返回,所以每个结果就重复了一次
public List<TreeNode> generateTrees(int n) {
List<TreeNode> res = new ArrayList<TreeNode>();
if(n==0)
return res;
res = doGenerate(1,n);
return res;
}
private List<TreeNode> doGenerate(int start, int end){
List<TreeNode> child = new ArrayList<TreeNode>();
if(start>end){
child.add(null);//这里不要忘记加上null
return child;
}
for(int index=start;index<=end;index++){
List<TreeNode> left = doGenerate(start,index-1);
List<TreeNode> right = doGenerate(index+1,end);
for(TreeNode l:left){
for(TreeNode r:right){
TreeNode root = new TreeNode(index);
root.left = l;
root.right = r;
child.add(root);
}
}
}
return child;
}

本文探讨了如何计算n个数字可构造的不同二叉搜索树的总数,并提供了生成这些树的具体结构的算法。通过递归公式,我们能够求解特定数量的节点所能形成的独特BST数量,同时,也深入解析了如何枚举并构建所有可能的BST结构。
3395

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



