-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
tries_using_map.cpp
146 lines (141 loc) · 3.13 KB
/
tries_using_map.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
struct node
{
bool word_end;
map<char,node*> m;
};
node* getnode(){
node* temp = new node;
temp->word_end =false;
temp->m = map<char,node*>();
return temp;
}
node* insert(node* start,string s){
int i=0,n=s.size();
for(i=0;i<n;i++)
{
map<char,node*>::iterator it = start->m.find(s[i]);
if(it==start->m.end())
{
node* temp = getnode();
start->m.insert(make_pair(s[i],temp));
start = temp;
}
else
start = (*it).second;
}
start->word_end = true;
}
bool find(node* start,string s){
int i=0,n=s.size();
for(i=0;i<n;i++)
{
map<char,node*>::iterator it = start->m.find(s[i]);
if(it==start->m.end())
return false;
start = (*it).second;
}
if(start->word_end==true)
return true;
else
return false;
}
bool delete_util(node* start,string s,int begin,int end){
if(begin==end)
{
if(!start->word_end)
return false;
else
{
if(!start->m.size())
{
free(start);
return true;
}
else
start->word_end = false;
}
}
else
{
map<char,node*>::iterator it = start->m.find(s[begin]);
if(it==start->m.end())
return false;
bool temp = delete_util((*it).second,s,begin+1,end);
if(temp==false)
return false;
else
{
start->m.erase(s[begin]);
if(start->m.size()==0)
{
free(start);
return true;
}
else
return false;
}
}
}
void delete_node(node* start,string s){
delete_util(start,s,0,s.size());
}
void level_order(node* start){
queue<node*> q;
q.push(start);
q.push(getnode());
while(!q.empty())
{
node* temp = q.front();
q.pop();
if(temp->m.size()==0)
{
if(q.empty())
break;
cout<<"\n";
q.push(temp);
}
else
{
map<char,node*>::iterator it = temp->m.begin();
for(it;it!=temp->m.end();it++)
{
cout<<(*it).first;
node* t = (*it).second;
if(t->m.size()>0)
q.push(t);
}
cout<<" ";
}
}
}
void print_words(node* start,string s){
if(start->m.size()==0){
if(s.size()!=0)
cout<<s<<" ";
}
for(map<char,node*>::iterator it=start->m.begin();it!=start->m.end();it++)
print_words((*it).second,s+(*it).first);
}
int main()
{
node* start = getnode();
int t;
cin>>t;
string s;
while(t--)
{
cin>>s;
insert(start,s);
}
//level_order(start);
//To find a something in the trie
//cout<<find(start,"william")<<"\n";
//To delete from trie
//delete_node(start,"wilsoni");
//To print all the data from trie
//print_words(start,"");
return 0;
}