Given an integer 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.
sequence
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
这个题目是上一道二叉搜索树的延伸,上一道题目是说给定的数字,让我们找出总的二叉搜索树的数量,这一道题直接很粗暴的要求返回所有的二叉搜索树,这一道题目也是很典型的DP问题的题目,从1开始建立二叉搜索树,随着数字的变大不断的扩充数的规模,每一次添加进去的数字都是当前的所有数字里面最大的那个数字,所以插入的数字只有两种情况,要么是作为根节点插入的,要么就只能作为右节点插入,右节点插入的话在所有的右节点的路上都是可以插入的。下面来看看程序就好了:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* clone(TreeNode* node) {
if (node == NULL)
return NULL;
TreeNode* newroot =
new TreeNode(node -> val);
newroot -> left = clone(node -> left);
newroot -> right = clone(node -> right);
return newroot;
}
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> vec;
stack<TreeNode*> sta1;
stack<TreeNode*> sta2;
int size = 0;
TreeNode* node1 = NULL;
TreeNode* node2 = NULL;
TreeNode* clo = NULL;
TreeNode* root = NULL;
TreeNode* temp = NULL;
TreeNode* temp1 = NULL;
TreeNode* temp2 = NULL;
TreeNode* temp3 = NULL;
TreeNode* temp4 = NULL;
int depth = 0;
int size1 = 0;
int size2 = 0;
if (n <= 0)
return vec;
node1 = new TreeNode(1);
sta1.push(node1);
for (int i = 2; i <= n; i++) {
size1 = sta1.size();
size2 = sta2.size();
if (size1) {
while (sta1.size()) {
root = sta1.top();
clo = clone(root);
//作为根节点插入进去了
node1 = new TreeNode(i);
node1 -> left = root;
sta2.push(node1);
temp1 = clo;
for(int j = 0;clo -> right!=NULL;j++) {
node2 = new TreeNode(i);
depth = j + 1;
temp2 = clone(temp1);
temp3 = temp2;
temp4 = temp3;
while (depth--) {
temp4 = temp3;
temp3 = temp3 -> right;
}
temp4 -> right = node2;
node2 -> left = temp3;
sta2.push(temp2);
clo = clo -> right;
}
node2 = new TreeNode(i);
clo -> right = node2;
sta2.push(temp1);
sta1.pop();
}
} else if (size2) {
while (sta2.size()) {
root = sta2.top();
clo = clone(root);
node1 = new TreeNode(i);
node1 -> left = root;
sta1.push(node1);
temp1 = clo;
for(int j = 0;clo->right!=NULL;j++){
depth = j + 1;
node2 = new TreeNode(i);
temp2 = clone(temp1);
temp3 = temp2;
temp4 = temp3;
while (depth--) {
temp4 = temp3;
temp3 = temp3 -> right;
}
temp4 -> right = node2;
node2 -> left = temp3;
sta1.push(temp2);
clo = clo -> right;
}
node2 = new TreeNode(i);
clo -> right = node2;
sta1.push(temp1);
sta2.pop();
}
}
}
size1 = sta1.size();
size2 = sta2.size();
if (size1) {
while (sta1.size()) {
vec.push_back(sta1.top());
sta1.pop();
}
} else if (size2) {
while (sta2.size()) {
vec.push_back(sta2.top());
sta2.pop();
}
}
return vec;
}
};
这道题比较重要的思路就是复制函数的设计,在每一次要插入新的节点的时候需要复制一下原来的二叉树,再将新的节点插入进去,由于这里涉及使用递归来实现,所以我不是很能确定它的空间复杂度与时间复杂度,这就有点尴尬了。