Trie树,又称为字典树或者叫键树,是一种hash树的改进。经常应用于统计和排序大量的字符串,或者查找字符串。
Trie树的结构如下:
数据结构如下:
typedef struct iNode
{
char symbol;
iNode *first; //子节点的第一个节点
iNode *next; //邻居节点
}iNode;
完整代码如下:


1 #include<iostream> 2 #include<iomanip> 3 using namespace std; 4 5 typedef struct iNode 6 { 7 char symbol; 8 iNode *first; 9 iNode *next; 10 }iNode; 11 12 class Trie 13 { 14 private: 15 iNode *root; 16 public: 17 Trie(); 18 void insert(char *word); 19 void print(iNode *curr); 20 void show(); 21 void search(char *word); 22 }; 23 24 Trie::Trie() 25 { 26 iNode *loc = new iNode; 27 loc->first = NULL; 28 loc->next = NULL; 29 root = loc; 30 } 31 32 void Trie::insert(char *word) 33 { 34 iNode *loc; 35 loc = root; 36 while(*word) 37 { 38 if(loc->first) 39 { 40 if(loc->first->symbol == *word) 41 { 42 cout<<loc->first->symbol<<" exist"<<endl; 43 loc = loc->first; 44 } 45 else 46 { 47 iNode *temploc; 48 temploc = loc->first; 49 for(loc = loc->first->next; loc; loc = loc->next) 50 { 51 //cout<<"TEST1"<<endl; 52 if(loc->symbol == *word) 53 { 54 cout<<loc->symbol<<" exist"<<endl; 55 break; 56 } 57 temploc = loc; 58 } 59 if(!loc) 60 { 61 iNode *temp = new iNode; 62 temp->symbol = *word; 63 temp->first = NULL; 64 temp->next = NULL; 65 temploc->next = temp; 66 cout<<"Add new symbol: "<<temploc->next->symbol<<endl; 67 } 68 loc = temploc->next; 69 } 70 } 71 else 72 { 73 iNode *temp = new iNode; 74 temp->symbol = *word; 75 temp->first = NULL; 76 temp->next = NULL; 77 loc->first = temp; 78 cout<<"Add new symbol: "<<loc->first->symbol<<endl; 79 loc = loc->first; 80 } 81 word++; 82 83 } 84 } 85 86 void Trie::print(iNode *cur) 87 { 88 iNode *loc; 89 loc = cur; 90 while(loc) 91 { 92 iNode *temp = loc, *temp1 = loc; 93 if(temp) 94 { 95 print(temp->next); 96 cout<<setw(5)<<temp->symbol; 97 } 98 cout<<endl; 99 loc = loc->first; 100 } 101 cout<<endl; 102 } 103 104 void Trie::show() 105 { 106 print(this->root->first); 107 } 108 109 void Trie::search(char *word) 110 { 111 iNode *loc; 112 char *ch = word; 113 loc = this->root->first; 114 while(*word) 115 { 116 while(loc) 117 { 118 if(loc->symbol == *word) 119 { 120 cout<<loc->symbol<<" exists in the trie"<<endl; 121 break; 122 } 123 else 124 { 125 loc = loc->next; 126 } 127 } 128 if(loc == NULL) 129 { 130 cout<<"String \""<<ch<<"\" not exist in the trie"<<endl<<endl; 131 break; 132 } 133 word++; 134 loc = loc->first; 135 } 136 if(*word == '\0') 137 { 138 cout<<"String \""<<ch<<"\" exists in the trie"<<endl<<endl; 139 } 140 141 } 142 143 int main() 144 { 145 Trie t; 146 t.insert("ab"); 147 t.show(); 148 t.insert("abc"); 149 t.show(); 150 t.insert("search"); 151 t.show(); 152 t.insert("serah"); 153 t.show(); 154 t.search("abc"); 155 t.search("abd"); 156 t.search("serah"); 157 158 return 0; 159 }