1 #include <iostream> 2 #include <string> 3 using namespace std; 4 #define ALPHABET_SIZE 26 5 6 typedef struct trie_node 7 { 8 int count; // 记录该节点代表的单词的个数 9 trie_node *children[ALPHABET_SIZE]; // 各个子节点 10 }*trie; 11 12 trie_node* create_trie_node() 13 { 14 trie_node* pNode = new trie_node(); 15 pNode->count = 0; 16 for(int i=0; i<ALPHABET_SIZE; ++i) 17 pNode->children[i] = NULL; 18 return pNode; 19 } 20 21 void trie_insert(trie root, char* key) 22 { 23 trie_node* node = root; 24 char* p = key; 25 while(*p) 26 { 27 if(node->children[*p-'a'] == NULL) 28 { 29 node->children[*p-'a'] = create_trie_node(); 30 } 31 node = node->children[*p-'a']; 32 ++p; 33 } 34 node->count += 1; 35 } 36 /* 37 查询:不存在返回0,存在返回出现的次数 38 */ 39 int trie_search(trie root, char* key) 40 { 41 trie_node* node = root; 42 char* p = key; 43 while(*p && node!=NULL) 44 { 45 node = node->children[*p-'a']; 46 ++p; 47 } 48 if(node == NULL) 49 return 0; 50 else 51 return node->count; 52 } 53 54 int main() 55 { 56 // 关键字集合 57 char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"}; 58 trie root = create_trie_node(); 59 // 创建trie树 60 for(int i = 0; i < 8; i++) 61 trie_insert(root, keys[i]); 62 // 检索字符串 63 char s[][32] = {"Present in trie", "Not present in trie"}; 64 printf("%s --- %s\n", "the", trie_search(root, "the")>0?s[0]:s[1]); 65 printf("%s --- %s\n", "these", trie_search(root, "these")>0?s[0]:s[1]); 66 printf("%s --- %s\n", "their", trie_search(root, "their")>0?s[0]:s[1]); 67 printf("%s --- %s\n", "thaw", trie_search(root, "thaw")>0?s[0]:s[1]); 68 return 0; 69 }