-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtrie.cpp
78 lines (62 loc) · 1.61 KB
/
trie.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
#include<bits/stdc++.h> //sahumohit
#define ll long long
#define mod 1000000007
using namespace std;
const int alphasize = 26;
struct trienode
{
//one trie node contains 26 characters and a bool indicator indicate it is end of word or not.
trienode * children[alphasize];
bool isendofword;
};
trienode* getnode ()
{
trienode * temp = new trienode;
for(int i=0 ; i<alphasize ; i++)
{
temp->children[i]=NULL;
}
temp->isendofword = false;
return temp;
}
void insertt (trienode * root , string key)
{
trienode * temp = root;
for(int i=0 ; i<key.length() ; i++)
{
int index = key[i]-'a';
if(!temp->children[index])
temp->children[index]=getnode();
temp = temp->children[index];
}
temp->isendofword = true;
}
bool searchh (trienode * root , string key)
{
trienode * temp = root;
for(int i=0 ; i<key.length() ; i++)
{
int index = key[i]-'a';
if(!temp->children[index])
return false;
temp = temp->children[index];
}
return (temp!=NULL && temp->isendofword);
}
int main()
{
string keys[] = {"the", "a", "there",
"answer", "any", "by",
"bye", "their" };
int n = sizeof(keys)/sizeof(keys[0]);
struct trienode *root = getnode();
// Construct trie
for (int i = 0; i < n; i++)
insertt(root, keys[i]);
// Search for different keys
searchh(root, "the")? cout << "Yes\n" :
cout << "No\n";
searchh(root, "these")? cout << "Yes\n" :
cout << "No\n";
return 0;
}