struct Node
{
map<char, Node*> children;
bool is_end_of_word;
Node() : is_end_of_word(false) {}
Node(char key, Node* next) : is_end_of_word(false) { children.insert(map<char, Node*>::value_type(key, next)); }
};
class Trie
{
public:
Trie(void);
~Trie(void);
void tire_insert(const string& input);
bool tire_search(const string& input);
Node* get_root() { return root_; }
private :
void clear_node(Node* node);
Node* root_;
};
Trie::Trie(void)
{
root_ = new Node();
}
void Trie::clear_node(Node* node)
{
if (node->children.size() == 0)
delete node;
else {
for (int i = 0; i < node->children.size(); i++)
clear_node(node->children.at(i));
}
}
Trie::~Trie(void)
{
clear_node(root_);
}
void Trie::tire_insert(const string& input)
{
Node* tmp = root_;
for (int i = 0; i < input.size(); i++) {
char c = input.at(i);
if (tmp->children.find(c) == tmp->children.end()) {
tmp->children.insert(map<char, Node*>::value_type(c, new Node()));
}
tmp = tmp->children.at(c);
if (i == input.size() - 1) {
tmp->is_end_of_word = true;
}
}
}
bool Trie::tire_search(const string& input)
{
Node* tmp = root_;
for (int i = 0; i < input.size(); i++) {
char c = input.at(i);
if (tmp->children.find(c) != tmp->children.end()) {
tmp = tmp->children.at(c);
}
else {
return false;
}
}
return tmp->is_end_of_word;
}
int main()
{
Trie tire;
tire.tire_insert(string("abc"));
tire.tire_insert(string("abc"));
tire.tire_insert(string("abcd"));
tire.tire_insert(string("dfsfsfewr"));
cout << tire.tire_search(string("abcd")) << endl;
cout << tire.tire_search(string("dfsfsfewr")) << endl;
cout << tire.tire_search(string("abcd")) << endl;
cout << tire.tire_search(string("abc")) << endl;
cout << tire.tire_search(string("ab")) << endl;
system("pause");
return 0;
}