-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathSearchInTries.cpp
69 lines (59 loc) · 1.47 KB
/
SearchInTries.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
class TrieNode {
public:
char data;
TrieNode **children;
bool isTerminal;
TrieNode(char data) {
this->data = data;
children = new TrieNode *[26];
for (int i = 0; i < 26; i++) {
children[i] = NULL;
}
isTerminal = false;
}
};
class Trie {
TrieNode *root;
public:
Trie() {
root = new TrieNode('\0');
}
void insertWord(TrieNode *root, string word) {
// Base case
if (word.size() == 0) {
root->isTerminal = true;
return;
}
// Small Calculation
int index = word[0] - 'a';
TrieNode *child;
if (root->children[index] != NULL) {
child = root->children[index];
} else {
child = new TrieNode(word[0]);
root->children[index] = child;
}
// Recursive call
insertWord(child, word.substr(1));
}
void insertWord(string word) {
insertWord(root, word);
}
bool search(TrieNode *root, string word) {
// Base Case
if (word.size() == 0)
return root->isTerminal;
// Small Calculation
int index = word[0] - 'a';
TrieNode *child = root->children[index];
if (child != NULL) {
return search(child, word.substr(1));
}
else {
return false;
}
}
bool search(string word) {
return search(root, word);
}
};