-
Notifications
You must be signed in to change notification settings - Fork 0
/
allpossiblefbts.cpp
77 lines (75 loc) · 1.62 KB
/
allpossiblefbts.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
bool equal(TreeNode* r1,TreeNode* r2)
{
if((r1&&r2)||(!r1&&!r2))
if(r1&&r2)
return equal(r1->right,r2->right)&&equal(r1->left,r2->left);
else return true;
else return false;
}
TreeNode* clone(TreeNode* root)
{
if(root)
{
TreeNode* final=child();
final->left= clone(root->left);
final->right= clone(root->right);
return final;
}
else return NULL;
}
TreeNode* child()
{
TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
root->val=0;
root->left=NULL;
root->right=NULL;
return root;
}
void traversal(map<int,vector<TreeNode*>>& m,TreeNode* root,TreeNode* temp,int target)
{
if(temp->left)
{
traversal(m,root,temp->left,target);
traversal(m,root,temp->right,target);
}
else
{
temp->left=child();
temp->right=child();
bool val=false;
for(int i=0;i<m[target].size();++i)
val=val||equal(m[target].at(i),root);
TreeNode* final;
final=clone(root);
if(!val)
m[target].push_back(final);
temp->left=NULL;
temp->right=NULL;
}
}
vector<TreeNode*> makeTree(map<int,vector<TreeNode*>>&m, int target)
{
if(m.find(target)==m.end())
{
if(target==1)
{
TreeNode* root=child();
vector<TreeNode*> ret;
ret.push_back(root);
m[target]=ret;
}
else
{
vector<TreeNode*> temp=makeTree(m,target-2);
vector<TreeNode*> ret;
m[target]=ret;
for(int i=0;i<temp.size();++i)
traversal(m,temp[i],temp[i],target);
}
}
return m[target];
}
vector<TreeNode*> allPossibleFBT(int N) {
map<int,vector<TreeNode*>> m;
return makeTree(m,N);
}