-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy path95-Unique-Binary-Search-Trees-II.cpp
51 lines (50 loc) · 1.35 KB
/
95-Unique-Binary-Search-Trees-II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution
{
public:
TreeNode *clone(TreeNode *root)
{
if (root == nullptr)
return nullptr;
TreeNode *newroot = new TreeNode(root->val);
newroot->left = clone(root->left);
newroot->right = clone(root->right);
return newroot;
}
vector<TreeNode *> generateTrees(int n)
{
vector<TreeNode *> res(1, nullptr);
for (int i = 1; i <= n; i++)
{
vector<TreeNode *> tmp;
for (int j = 0; j < res.size(); j++)
{
TreeNode *oldroot = res[j];
TreeNode *root = new TreeNode(i);
TreeNode *target = clone(oldroot);
root->left = target;
tmp.push_back(root);
if (oldroot != nullptr)
{
TreeNode *tmpold = oldroot;
while (tmpold->right != nullptr)
{
TreeNode *nonroot = new TreeNode(i);
TreeNode *tright = tmpold->right;
tmpold->right = nonroot;
nonroot->left = tright;
TreeNode *target = clone(oldroot);
tmp.push_back(target);
tmpold->right = tright;
tmpold = tmpold->right;
}
tmpold->right = new TreeNode(i);
TreeNode *target = clone(oldroot);
tmp.push_back(target);
tmpold->right = nullptr;
}
}
res = tmp;
}
return res;
}
};