-
Notifications
You must be signed in to change notification settings - Fork 0
/
208. Implement Trie (Prefix Tree).cpp
116 lines (103 loc) · 2.57 KB
/
208. Implement Trie (Prefix Tree).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
class TrieNode{
public:
bool isTerminal;
TrieNode *children[26];
char data;
TrieNode(char ch)
{
data=ch;
for(int i=0;i<26;i++)
{
children[i]=NULL;
}
isTerminal=false;
}
};
class Trie {
public:
TrieNode* root;/*this is important for your trie to get memory allocated for that*/
Trie() {
root = new TrieNode('/0');
}
void insertUtil(string word, TrieNode* rootLocal)
{
// cout<<rootLocal->data<<"\n";
TrieNode* child;
if(word.size()==0)
{
// cout<<"isTerminal "<<rootLocal->data<<"\n";
rootLocal->isTerminal=true;
return;
}
int index= word[0]-'a';
// cout<<"index insert "<<index<<endl;
if(rootLocal->children[index]!=NULL)//PRESENT
{
child=rootLocal->children[index];
// cout<<"present insert "<<child->data<<"\n";
}
else//ABSENT
{
child=new TrieNode(word[0]);
rootLocal->children[index]=child;
// cout<<"absent insert "<<child->data<<"\n";
}
insertUtil(word.substr(1),child);
}
bool searchUtil(string word, TrieNode* rootLocal)
{
// cout<<rootLocal->data<<"\n";
TrieNode* child;
if(word.length()==0)
{
return rootLocal->isTerminal;
}
int index= word[0]-'a';
// cout<<"index "<<index<<endl;
if(rootLocal&&rootLocal->children[index]!=NULL)//PRESENT
{
child=rootLocal->children[index];
// cout<<"present "<<child->data<<"\n";
}
else
{
return false;
}
return true&&searchUtil(word.substr(1),child);
}
bool startsWithUtil(string prefix, TrieNode* rootLocal)
{
TrieNode* child;
if(prefix.size()==0)//base condition to exit when prefix is traversed
{
return true;
}
int index=prefix[0]-'a';
//present
if(rootLocal->children[index]!=NULL)
{
child=rootLocal->children[index];
}
else
{
return false;
}
return startsWithUtil(prefix.substr(1),child);
}
void insert(string word) {
insertUtil(word,root);
}
bool search(string word) {
return searchUtil(word,root);
}
bool startsWith(string prefix) {
return startsWithUtil(prefix,root);
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/