(i)
【题目描述】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.
1 3 3 2 1
\ / / / \
3 2 1 1 3 2
/ / \
2 1 2 3
【解题思路】关键是递推过程的分析,n个点中每个点都可以作为root,当 i 作为root时,小于 i 的点都只能放在其左子树中,大于 i 的点只能放在右子树中,此时只需求出左、右子树各有多少种,二者相乘即为以 i 作为root时BST的总数。开始时,我尝试用递归实现,但是超时了,可见系统对运行时间有要求。因为递归过程中存在大量的重复计算,从n一层层往下递归,故考虑类似于动态规划的思想,让底层的计算结果能够被重复利用,故用一个数组存储中间计算结果(即 1~n-1 对应的BST数目),这样只需双层循环即可。
【考查内容】树
class Solution {
public:
int numTrees(int n) {
vector<int> num;
num.push_back(1);
for(int i=1; i<=n; i++){
num.push_back(0);
if(i<3)
num[i]=i;
else{
for(int j=1; j<=i; j++)
num[i]+=num[j-1]*num[i-j];
}
}
return num[n];
}
};
(ii)
【题目描述】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
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
输出1到n组成的所有二叉搜索树的结构
【解题思路】选定1-n的一个数字i作为根节点、0到i-1是左子树, i+1-n是右子树,两层循环
【考查内容】树
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> generateTrees(int n){
return create(1, n);
}
vector<TreeNode*> create(int left, int right){
vector<TreeNode*> res;
if (left>right){
res.push_back(NULL);
return res;
}
for (int i=left; i<=right; i++){
vector<TreeNode*> leftTree = create(left, i-1);
vector<TreeNode*> rightTree = create(i+1, right);
for (int j = 0; j<leftTree.size(); j++){
for (int k = 0; k<rightTree.size(); k++){
TreeNode* root = new TreeNode(i);
root->left = leftTree[j];
root->right = rightTree[k];
res.push_back(root);
}
}
}
return res;
}
};