-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie_insert_search.cpp
129 lines (100 loc) · 2.27 KB
/
trie_insert_search.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
117
118
119
120
121
122
123
124
125
126
127
128
129
//assuming that the count == 0 in a node represents not a leaf
// count > 0 value represents a leaf in a trie
//
#include<iostream>
#include<string.h>
#define ALPHABET_SIZE 26
#define CHAR_TO_INDEX(c) ((int)c - (int) 'a')
#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])
using namespace std;
struct TrieNode
{
int val;
struct TrieNode* child[ALPHABET_SIZE];
};
class Trie
{
int count;
struct TrieNode* root;
struct TrieNode* getNode();
public:
Trie();
struct TrieNode* getRoot()
{
return this->root; //root is dummy node
}
void insert(char key[]);
bool search(char key[]);
};
Trie::Trie()
{
this->root = getNode();
this->count = 0;
}
void Trie::insert(char key[])
{
struct TrieNode* pTrieNode = getRoot();
int level;
int length = strlen(key);
this->count++;
for (level = 0; level < length; level++)
{
int index = CHAR_TO_INDEX(key[level]);
if(!pTrieNode->child[index])
{
pTrieNode->child[index] = getNode();
pTrieNode = pTrieNode->child[index];
}
else
{
pTrieNode = pTrieNode->child[index];
}
}
//make last node as the leaf node
pTrieNode->val = this->count;
}
bool Trie::search(char key[])
{
struct TrieNode* pTrieNode = this->getRoot();
int length = strlen(key);
int i;
for (i = 0; i < length; i++)
{
int index = CHAR_TO_INDEX(key[i]);
if(!pTrieNode->child[index])
{
return false;
}
pTrieNode = pTrieNode->child[index];
}
return (pTrieNode != NULL && pTrieNode->val != 0);
}
struct TrieNode* Trie::getNode()
{
struct TrieNode* pTrieNode = NULL;
pTrieNode = new struct TrieNode;
if(pTrieNode)
{
int i;
pTrieNode->val = 0;
for(i = 0; i < ALPHABET_SIZE; i++)
{
pTrieNode->child[i] = NULL;
}
}
return pTrieNode;
}
int main()
{
char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"};
Trie trie;
for(int i = 0; i < ARRAY_SIZE(keys); i++)
{
trie.insert(keys[i]);
}
if(trie.search("theis"))
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}