Trie树模板(插入和查询)

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef struct TrieNode{
 5     bool flag;
 6     TrieNode *next[26];
 7     TrieNode(){
 8         flag = false;
 9         memset(next, 0, sizeof(next));
10     }
11 }TrieNode, *Trie;
12 
13 TrieNode *InitTrieNode(){
14     TrieNode *p = new TrieNode;
15     return p;
16 }
17 
18 void InsertNode(Trie root, char *word){
19     Trie p = root;
20     char *ch = word;
21     int id;
22     while(*ch){
23         id = *ch - 'a';
24         if (p->next[id] == NULL)
25             p->next[id] = InitTrieNode();
26         p = p->next[id];
27         ++ch;
28     }
29     p->flag = true;
30 }
31 
32 bool TrieSearch(Trie root, char *word){
33     Trie p = root;
34     char *ch = word;
35     int id;
36     bool ans = false;
37     while(*ch){
38         id = *ch - 'a';
39         if (p->next[id] == NULL)
40             return false;
41         p = p->next[id];
42         ++ch;
43     }
44     return p->flag;
45 }
46 
47 int main()
48 {
49     Trie root = InitTrieNode();
50     cout<<"请输入需要的单词数:"<<endl;
51     int n;
52     char str[25];
53     cin>>n;
54     while(n--){
55         cout<<"请输入单词:"<<endl;
56         cin>>str;
57         InsertNode(root, str);
58     }
59     cout<<endl<<"请输入需要的查询数:"<<endl;
60     cin>>n;
61     while(n--){
62         cout<<"请输入单词:"<<endl;
63         cin>>str;
64         if (TrieSearch(root, str)) cout<<"该单词存在"<<endl<<endl;
65         else cout<<"该单词不存在"<<endl<<endl;
66     }
67 
68     return 0;
69 }

 

posted @ 2017-01-12 22:04  Robin!  阅读(225)  评论(0编辑  收藏  举报