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.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
这题和之前的Unique Binary Search Tree基本思路差不多,就是操作难度大了些。上一题只要求求出有多少种可能的结构,这次要求输出所有可能的结构。但是递归的思想还是一致的,如果说上一题还能说是dynamic programming,这题就是典型的divide and conquer。这里需要我们抓住的就是递归函数的返回值类型相同,我们最终要的是一个包含所有结构的数列,数列每个元素分别是不同结构的root。当然这是个NP的问题,我们需要在循环中使用递归,首先得循环肯定是从1到n每个轮流作为根节点,然后每次选定根节点之后,左子树和右子树的选择就是变成了同样性质的小规模问题,分别是i-1和n-i, 所以对于小问题我们同样返回一个数列,存着所有可能结果的根节点,那么对于大问题来说,只需要从两边的小问题的返回序列中依次选取不同的子树来作为一个完整的结果存起来。弄明白这个递归的过程,代码不言而喻。
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res;
if (n == 0) return res;
else return helper(1, n);
}
vector<TreeNode*> helper (int begin, int end) {
vector<TreeNode*> res;
if (begin > end) {
res.push_back(NULL);
return res;
}
for (int i = begin; i <= end; i++) {
vector<TreeNode*> lefttree = helper(begin, i-1);
vector<TreeNode*> righttree = helper(i+1, end);
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;
}
};
这里特地邀注明的一点就是在任何组成的vector里,NULL都会作为成员参与计数,所以不用担心左子树是NULL的情况下没法进行右子树的循环选择问题。
update:
方法二:非递归
dynamic programming
每添加一个新的元素,可以考虑会有集中添加的情况产生。
1. 新元素作为新的根节点,这个时候之前所有已经产生的tree都可以作为它的左子树。
2. 新元素作为之前树的右子树中的一员。可以执行重复操作,用新节点替代之前的右子树,右子树成为新节点的左子树。这一点对于右子树中的每一个最右侧的小右子树都成立。
3. 注意的一点就是,我们要对之前的树反复操作,所以逐一在操作之后新建内存把结果拷贝过来,然后放入新的结果中,并且恢复原有的树。
代码如下:
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res;
if (n < 1) return res;
res.push_back(nullptr);
for (int i = 1; i <= n; i++) {
vector<TreeNode*> tmpres;
TreeNode* newnode = new TreeNode(i);
for (int j = 0; j < res.size(); j++) {
// newnode is the new root
TreeNode* oldroot = res[j];
newnode->left = oldroot;
TreeNode* target = clone(newnode);
tmpres.push_back(target);
// newnode is not the root, just a node
if (oldroot != NULL) {
TreeNode* tmproot = oldroot;
while (tmproot->right != NULL) {
TreeNode* tmpright = tmproot->right;
tmproot->right = newnode;
newnode->left = tmpright;
TreeNode* target = clone(oldroot);
tmpres.push_back(target);
tmproot->right = tmpright;
tmproot = tmpright;
}
tmproot->right = newnode;
newnode->left = NULL;
TreeNode* target = clone(oldroot);
tmpres.push_back(target);
tmproot->right = NULL;
}
}
res = tmpres;
}
return res;
}
TreeNode* clone(TreeNode* oldnode) {
if (oldnode == nullptr) return nullptr;
TreeNode* newnode = new TreeNode(oldnode->val);
newnode->left = clone(oldnode->left);
newnode->right = clone(oldnode->right);
return newnode;
}
};