Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 275f94f

Browse files
Create Tries Implementation(Search Word in Dictionary)
1 parent 671ba1f commit 275f94f

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#include<iostream>
2+
#include<string>
3+
using namespace std;
4+
class TrieNode{
5+
public:
6+
char data;
7+
TrieNode **children;
8+
bool isTerminal;
9+
TrieNode(char data){
10+
this->data=data;
11+
children=new TrieNode*[26];
12+
for(int i=0;i<26;i++){
13+
children[i]=NULL;
14+
}
15+
isTerminal=false;
16+
}
17+
};
18+
class Trie{
19+
TrieNode* root;
20+
public:
21+
Trie(){
22+
root=new TrieNode('0円');
23+
}
24+
void insertWord(TrieNode* root,string word){
25+
//base case
26+
if(word.size()==0){
27+
root->isTerminal=true;
28+
return;
29+
}
30+
//small calculation
31+
int index=word[0]-'a';
32+
TrieNode* child;
33+
if(root->children[index]!=NULL){
34+
child=root->children[index];
35+
}
36+
else{
37+
child=new TrieNode(word[0]);
38+
root->children[index]=child;
39+
}
40+
//recursive call
41+
insertWord(child,word.substr(1));
42+
}
43+
//For user
44+
void insertWord(string word){
45+
insertWord(root,word);
46+
}
47+
bool search(TrieNode* root,string word){
48+
if(word.length()==0){
49+
return root->isTerminal;
50+
}
51+
int index=word[0]-'a';
52+
TrieNode* child;
53+
if(root->children[index]!=NULL){
54+
child=root->children[index];
55+
}
56+
else{
57+
return false;
58+
}
59+
return search(child,word.substr(1));
60+
}
61+
bool search(string word){
62+
return search(root,word);
63+
}
64+
void removeWord(TrieNode* root,string word){
65+
//base case
66+
if(word.size()==0){
67+
root->isTerminal=false;
68+
return;
69+
}
70+
//small calculation
71+
TrieNode* child;
72+
int index=word[0]-'a';
73+
if(root->children[index]!=NULL){
74+
child=root->children[index];
75+
}
76+
else{
77+
//word not found
78+
return;
79+
}
80+
removeWord(child,word.substr(1));
81+
//remove child node if it is useless
82+
if(child->isTerminal==false){
83+
for(int i=0;i<26;i++){
84+
if(child->children[i]!=NULL){
85+
return;
86+
}
87+
}
88+
delete child;
89+
root->children[index]=NULL;
90+
}
91+
}
92+
void removeWord(string word){
93+
removeWord(root,word);
94+
}
95+
};
96+
int main(){
97+
Trie t;
98+
t.insertWord("and");
99+
t.insertWord("are");
100+
t.insertWord("dot");
101+
cout<<t.search("and")<<endl;
102+
t.removeWord("and");
103+
cout<<t.search("and")<<endl;
104+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /