Unique Binary Search Trees II
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 Trees I知道,我们的思路就是每次找不同的值作为根,然后分别递归构造左右子树,然后对子树进行重新组合。思路简单,但是最后还是费了很大的劲,主要是对于指针等问题没有搞清楚。对问题不够深度把握.
另外一种思路比较直接,就是直接分析规律,也是在做1的时候没有想到的,那就是i的二叉树可以根据i-1的二叉树直接构造出来,一共有两种情况:
1. i作为根节点,那么i-1的所有树都会是i的左子树
2. i不作为根节点,那么i的节点也必须在i-1的的每一个节点的右子树中,对于当前节点,节点i-1可以把当前节点的右子树作为当前节点的左子树,i节点作为当前节点的右子树。
代码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:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> ret;
recBuildBST(1, n, ret);
return ret;
}
void recBuildBST(int left1, int left2, vector<TreeNode*>& ret){
if (left1 > left2){
return ;
}
else if (left1 == left2){
TreeNode* t = new TreeNode(left1);
t->left = NULL;
t->right = NULL;
ret.push_back(t);
}
for (int i = left1; i <= left2; ++i){
vector<TreeNode*> lefts(0);
vector<TreeNode*> rights(0);
recBuildBST(left1, i-1, lefts);
recBuildBST(i+1, left2, rights);
if (!lefts.size()){
for (auto it2 = rights.begin(); it2 != rights.end(); ++it2){
TreeNode* t = new TreeNode(i);
t->left = NULL;
t->right = *it2;
ret.push_back(t);
}
}
else if (!rights.size()){
for (auto it1 = lefts.begin(); it1 != lefts.end(); ++it1){
TreeNode* t = new TreeNode(i);
t->left = *it1;
t->right = NULL;
ret.push_back(t);
}
}
else {
for (auto it1 = lefts.begin(); it1 != lefts.end(); ++it1){
for (auto it2 = rights.begin(); it2 != rights.end(); ++it2){
TreeNode* t = new TreeNode(i);
t->left = *it1;
t->right = *it2;
ret.push_back(t);
}
}
}
}
}
};
代码2
/**
* 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:
vector<TreeNode*> generateTrees(int n) {
if (n <= 0) return {};
vector<TreeNode*> pre({NULL});
vector<TreeNode*> cur;
for (int i = 1; i <= n; ++i){
for (auto it = pre.begin(); it != pre.end(); ++it){
TreeNode* new_root = new TreeNode(i);
TreeNode* old_root = copy(*it);
new_root->left = old_root;
new_root->right = NULL;
cur.push_back(new_root);
TreeNode* old_p = *it;
while (old_p){
TreeNode* new_node = new TreeNode(i);
TreeNode* tmpRight = old_p->right;
new_node->left = old_p->right;
old_p->right = new_node;
TreeNode* new_root = copy(*it);
cur.push_back(new_root);
old_p->right = tmpRight;
old_p = old_p->right;
}
}
pre.clear();
pre = cur;
cur.clear();
}
return pre;
}
TreeNode* copy(TreeNode* root){
if (!root) return NULL;
TreeNode* new_root = new TreeNode(root->val);
new_root->left = copy(root->left);
new_root->right = copy(root->right);
return new_root;
}
};