Skip to content

Commit 972f505

Browse files
Merge pull request matthewsamuel95#682 from av4l4nc14/add_better_version_trie
Added another implementation of Trie
2 parents 8a24d03 + 6b9d862 commit 972f505

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed

Data Structures/Trie/trie2.cpp

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
#include<bits/stdc++.h>
2+
#define pb push_back
3+
#define eb emplace_back
4+
#define mp make_pair
5+
#define mt make_tuple
6+
#define all(v) v.begin(),v.end()
7+
#define PI 3.14159265358979323
8+
#define endl '\n'
9+
#define hashmap unordered_map<char,node*>
10+
11+
using namespace std;
12+
13+
class node{
14+
public:
15+
char data;
16+
hashmap h;
17+
bool isTerminal;
18+
19+
node(char d)
20+
{
21+
data=d;
22+
isTerminal=false;
23+
}
24+
25+
};
26+
27+
28+
29+
class Trie{
30+
31+
node *root;
32+
33+
public:
34+
Trie(){
35+
root=new node('\0');
36+
}
37+
38+
void addWord(char* word)
39+
{
40+
node * temp=root;
41+
42+
for(int i=0;word[i]!='\0';i++)
43+
{
44+
char ch=word[i];
45+
if(temp->h.count(ch)==0)
46+
{
47+
node * child=new node(ch);
48+
temp->h[ch]=child;
49+
temp=child;
50+
}else
51+
temp=temp->h[ch];
52+
}
53+
temp->isTerminal=true;
54+
}
55+
56+
bool search(char* word)
57+
{
58+
node * temp=root;
59+
60+
for(int i=0;word[i]!='\0';i++)
61+
{
62+
char ch=word[i];
63+
if(temp->h.count(ch))
64+
{
65+
temp=temp->h[ch];
66+
}
67+
else
68+
return false;
69+
}
70+
71+
if(temp->isTerminal)
72+
return true;
73+
else
74+
return false;
75+
}
76+
77+
};
78+
79+
int main(){
80+
//char word[10][100]={"apple","code","vinegar"};
81+
Trie t;
82+
t.addWord("vinegar");
83+
t.addWord("vine");
84+
t.addWord("cinnamon");
85+
86+
cout<<t.search("vine")<<endl;
87+
cout<<t.search("ape")<<endl;
88+
89+
}
90+
91+

0 commit comments

Comments
 (0)