题目一:
Given n, how many structurally unique BSTs (binary search trees) that store values 1...n?
For example,
Given n = 3, there are a total of 5 unique BST's.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
思路:
建立count[]数组,存放从1到n每一个数对应的BST的个数。
对于数n,可能有多少个BST呢?这个是由它的根节点分布决定的,若根节点为root,左子树的个数就是count[root-1]的值,右子树的个数就是count[i-root]的值,两个解的乘积就是根节点为root,借点总数为i的所有BST的个数。将root从1到i遍历一遍,就得到了count[i],即i个结点的所有解。
实现代码如下:
public class Solution {
public int numTrees(int n) {
int[] count = new int[n+1];
count[0] = 1;
for (int i = 1; i <= n; i++) {
for (int root = 1; root <= i; root++) {
int left = count[root-1];
int right = count[i-root];
count[i] += left*right;
}
}
return count[n];
}
}
Unique Bin
题目二:
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
思路:
找到一个数作为根结点,剩余的数分别划入左子树或者右子树。
实现代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<TreeNode> generateTrees(int n) {
if(n<1){
return new ArrayList<TreeNode>();
}
return generateTrees(1,n);
}
//函数功能:树节点中的value由start~end构成的二叉搜索树的所有结果
private List<TreeNode> generateTrees(int start, int end) {
List<TreeNode> res=new ArrayList<TreeNode>();
if(end<start){
res.add(null);
return res;
}
for(int i=start;i<=end;i++){
//产生以i为根节点,start~i-1构成左子树,i+1~end构成右子树
List<TreeNode> leftSubTreeList=generateTrees(start,i-1);
List<TreeNode> rightSubTreeList=generateTrees(i+1,end);
//遍历并由根节点组合左子树和右子树构成最后的结果
for(TreeNode leftSubTree:leftSubTreeList){
for(TreeNode rightSubTree:rightSubTreeList){
TreeNode root=new TreeNode(i);
root.left=leftSubTree;
root.right=rightSubTree;
res.add(root);
}
}
}
return res;
}
}