-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.h
57 lines (44 loc) · 1.12 KB
/
trie.h
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
#ifndef TRIE_H
#define TRIE_H
#include <cassert>
#include <iostream>
#include <string>
#define NUM_LETTERS 26
struct trie_node {
bool flag;
trie_node *parent, *children[NUM_LETTERS];
trie_node(trie_node *parent = nullptr) : parent{parent} {
for (int i = 0; i < NUM_LETTERS; ++i)
children[i] = nullptr;
flag = false;
}
void destroy() {
for (int i = 0; i < NUM_LETTERS; ++i)
free(children[i]);
}
void traverse(std::string s) {
if (flag)
std::cout << s << std::endl;
for (int i = 0; i < NUM_LETTERS; ++i) {
if (children[i])
children[i]->traverse(s + std::string(1, 'a' + i));
}
}
};
struct trie {
trie_node *root;
trie() { root = new trie_node(); }
~trie() { root->destroy(); }
void insert(std::string s) {
trie_node *cur_node = root;
for (char c : s) {
if (cur_node->children[c - 'a'] == nullptr) {
cur_node->children[c - 'a'] = new trie_node(cur_node);
}
cur_node = cur_node->children[c - 'a'];
}
cur_node->flag = true;
}
void traverse() { root->traverse(""); }
};
#endif /* end of include guard: TRIE_H */