Skip to content

Commit 5ca989f

Browse files
authored
Merge pull request #328 from sandy2004/master
Create trie.cpp
2 parents 00b72d2 + 71f34ca commit 5ca989f

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

C++/trie.cpp

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
class trie{
5+
6+
public:
7+
char val;
8+
bool end=false;
9+
trie* children[26]={NULL};
10+
};
11+
12+
void insert(trie* root, string str)
13+
{
14+
trie* temp=root;
15+
for(int i=0; i<str.length(); i++)
16+
{
17+
if(!temp->children[str[i]-'a'])
18+
{
19+
temp->children[str[i]-'a']= new trie();
20+
}
21+
temp=temp->children[str[i]-'a'];
22+
}
23+
temp->end=true;
24+
cout<<"value successfully Inserted"<<endl;
25+
}
26+
27+
void search(trie* root, string str)
28+
{
29+
trie* temp=root;
30+
for(int i=0; i<str.length(); i++)
31+
{
32+
if(temp->children[str[i]-'a']==NULL)
33+
{
34+
cout<<" Given value Not Found"<<endl;
35+
36+
}
37+
temp=temp->children[str[i]-'a'];
38+
}
39+
if(temp->end==true)
40+
{
41+
cout<<" Given value successfully Found"<<endl;
42+
}
43+
else
44+
{
45+
cout<<" Given value Not Found"<<endl;
46+
}
47+
}
48+
49+
void del(trie* root, string str)
50+
{
51+
trie* temp=root;
52+
for(int i=0; i<str.length(); i++)
53+
{
54+
if(temp->children[str[i]-'a']==NULL)
55+
{
56+
cout<<"Given value is not present"<<endl;
57+
58+
}
59+
temp=temp->children[str[i]-'a'];
60+
}
61+
62+
if(temp->end==true)
63+
{
64+
temp->end=0;
65+
cout<<"value successfully deleted"<<endl;
66+
}
67+
else
68+
{
69+
cout<<"Given value is not present"<<endl;
70+
}
71+
72+
}
73+
int main()
74+
{
75+
trie* root=new trie();
76+
cout<<"please enter string"<<endl;
77+
string str;
78+
cin>>str;
79+
insert(root,str);
80+
search(root,str);
81+
del(root,str);
82+
return 0;
83+
}

0 commit comments

Comments
 (0)