-
Notifications
You must be signed in to change notification settings - Fork 38
/
trie_tree.hpp
162 lines (134 loc) · 3.04 KB
/
trie_tree.hpp
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#ifndef _TRIETREE_H_
#define _TRIETREE_H_
#include <vector>
#include <string>
#include <iostream>
template <typename T>
class trie_tree
{
public:
explicit trie_tree()
: root_( new node )
{
}
~trie_tree()
{
clear();
}
void clear()
{
clear( root_ );
root_ = new node;
}
trie_tree( const trie_tree & ) = delete;
trie_tree &operator=( const trie_tree & ) = delete;
private:
struct node;
using node_ptr = node *;
using value_ptr = T *;
static constexpr int R = 128;
node_ptr root_;
struct node
{
explicit node()
: value( nullptr ), next( R, nullptr )
{
}
~node()
{
if( value )
{
delete value;
}
}
value_ptr value;
std::vector<node_ptr> next;
};
public:
void insert( const std::string &key, const T &value )
{
insert( root_, key, value, 0 );
}
bool contains( const std::string &key ) const
{
return get( key ) != nullptr;
}
value_ptr get( const std::string &key ) const
{
node_ptr ptr = get( root_, key, 0 );
if( !ptr )
{
return nullptr;
}
// ptr->value may be a null pointer, that means no value corresponds to the key
return ptr->value;
}
std::vector<std::string> keys() const
{
return keysWithPrefix( "" );
}
std::vector<std::string> keysWithPrefix( const std::string &prefix ) const
{
std::vector<std::string> keys;
auto ptr = get( root_, prefix, 0 );
collect( ptr, prefix, keys );
return keys;
}
void collect( node_ptr ptr, const std::string &prefix, std::vector<std::string> &keys ) const
{
if( ptr == nullptr )
{
return;
}
if( ptr->value != nullptr )
{
keys.push_back( prefix );
}
char c = 0;
for( auto p : ptr->next )
{
collect( p, prefix + c, keys );
++c;
}
}
private:
void insert( node_ptr &ptr, const std::string &key, const T &value, int i )
{
if( !ptr )
{
ptr = new node;
}
if( i == key.size() )
{
ptr->value = new T( value );
return;
}
char index = key[i];
insert( ptr->next[index], key, value, i + 1 );
}
node_ptr get( node_ptr ptr, const std::string &key, int i ) const
{
if( !ptr )
{
return nullptr;
}
if( i == key.size() )
{
return ptr;
}
char index = key[i];
return get( ptr->next[index], key, i + 1 );
}
void clear( node_ptr ptr )
{
if( ptr )
{
for( auto p : ptr->next )
{
clear( p );
}
delete ptr;
}
}
};
#endif /* _TRIETREE_H_ */