# 95. Unique Binary Search Trees II

98人阅读 评论(0)

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

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;
}
};

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;
}
};
1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：20757次
• 积分：1708
• 等级：
• 排名：千里之外
• 原创：146篇
• 转载：4篇
• 译文：1篇
• 评论：2条
文章分类
评论排行
最新评论