#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_SIZE 26
struct TrieNode {
int char_count;
char ch;
TrieNode* son_char[MAX_SIZE];
};
void clear_node( TrieNode* node ) {
node->char_count = 0;
for ( int i = 0; i < MAX_SIZE; ++i ) {
node->son_char[i] = NULL;
}
}
void insert_string( TrieNode* root, string str ) {
const int str_len = str.length();
TrieNode* now_node = root;
for ( int i = 0; i < str_len; ++i ) {
const char ch = str[i] - 'a';
if ( now_node->son_char[ch] == NULL ) {
TrieNode* temp = ( TrieNode* )malloc( sizeof( TrieNode ) );
clear_node( temp );
temp->ch = ch;
now_node->son_char[ch] = temp;
}
now_node = now_node->son_char[ch];
now_node->char_count += 1;
}
}
int search_string( TrieNode* root, string str ) {
TrieNode* now_node = root;
const int str_len = str.length();
for ( int i = 0; i < str_len; ++i ) {
const char ch = str[i] - 'a';
now_node = now_node->son_char[ch];
if ( now_node == NULL )
return 0;
}
return now_node->char_count;
}
void delete_node( TrieNode* node ) {
for ( int i = 0; i < MAX_SIZE; ++i ) {
if ( node->son_char[i] != NULL )
delete_node( node->son_char[i] );
}
free( node );
}
int main() {
TrieNode* root = ( TrieNode* )malloc( sizeof( TrieNode ) );
clear_node( root );
int insert_test_num;
int search_test_num;
cout << "Enter insert_test_num: ";
cin >> insert_test_num;
for ( int i = 0; i < insert_test_num; ++i ) {
string str;
cout << "Enter str: ";
cin >> str;
insert_string( root, str );
}
cout << "Enter search_test_num: ";
cin >> search_test_num;
for ( int i = 0; i < search_test_num; ++i ) {
string str;
cout << "Enter str: ";
cin >> str;
int res = search_string( root, str );
if ( res )
cout << "String Is In Trie Tree: " << res << " Times." << endl;
else
cout << "String Is Not in Trie Tree." << endl;
}
delete_node( root );
return 0;
}