forked from piyush-kash/Hacktober2021-cpp-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UniqueBInarySearchTree
53 lines (41 loc) · 1.08 KB
/
UniqueBInarySearchTree
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
52
/** Given A, generate all structurally unique BST’s (binary search trees) that store values 1...A. ***/
class Binary{
public:
vector<TreeNode*> generate(int Start, int End)
{
vector<TreeNode*> v;
if(Start > End)
{
v.push_back(NULL);
return v;
}
if(Start == End)
{
v.push_back(new TreeNode(Start));
return v;
}
for(auto i=Start; i<=End; i++)
{
vector<TreeNode *> lft = generate(Start, i-1);
vector<TreeNode *> rgt = generate(i+1, End);
for(auto l : lft)
{
for(auto r : rgt)
{
TreeNode *root = new TreeNode(i);
root->left = l;
root->right = r;
v.push_back(root);
}
}
}
return v;
}
vector<TreeNode*> generateTrees(int n)
{
if(n == 0)
return vector<TreeNode*>();
else
return generate(1, n);
}
};