-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.cpp
More file actions
44 lines (40 loc) · 809 Bytes
/
Trie.cpp
File metadata and controls
44 lines (40 loc) · 809 Bytes
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
struct Trie {
Trie * child[26];
bool leaf;
};
Trie * createNode() {
Trie * link = (Trie * ) malloc(sizeof(Trie));
for (ll i = 0; i < 26; i++) {
link -> child[i] = NULL;
}
link -> leaf = false;
return link;
}
void insertWord(Trie * root, string s) {
Trie * ptr = root;
for (char c: s) {
int n = c - 'a';
if (ptr -> child[n] == NULL) {
ptr -> child[n] = createNode();
}
ptr = ptr -> child[n];
}
ptr -> leaf = true;
}
bool searchWord(Trie * root, string s) {
for (char c: s) {
int i = c - 'a';
if (root -> child[i]) {
root = root -> child[i];
}
}
return (root -> leaf);
}
void print(Trie * ptr) {
for (int i = 0; i < 26; i++) {
if (ptr -> child[i]) {
cout << (char)(i + 'a') << ' ';
print(ptr -> child[i]);
}
}
}