Reference: http://www.cnblogs.com/tanky_woo/archive/2010/09/24/1833717.html
#include <iostream>#include<string.h>using namespacestd;Const intmax= -;structtrie{Trie*Next[max]; intV//as needed, 1 means no such word, 1 means there is this word}; Trie*root=NewTrie;voidCreatetrie (Char*str) { intLen =strlen (str); Trie*p = root, *Q; for(intI=0; i<len; ++i) {intid = str[i]-'a'; if(P->next[id] = =NULL) { //q = (Trie *) malloc (sizeof (Trie));Q =NewTrie; Q->v =1;//Initial v==1 for(intj=0; j<max; ++j) Q->NEXT[J] =NULL; P->next[id] =Q; } P= p->Next[id]; } P->v =-1;//if at the end, change V to 1 to indicate}intFindtrie (Char*str) { intLen =strlen (str); Trie*p =Root; for(intI=0; i<len; ++i) {intid = str[i]-'a'; P= p->Next[id]; if(p = = NULL)//if it is an empty set, the string that is prefixed by this is not saved return 0; if(P->v = =-1)//a string already in the character set is the prefix of this string return 1; } return 2;//This string is the prefix of a string in the character set}intDeletetrie (trie*T) { inti; if(t==NULL)return 0; for(i=0; i<max; i++) { if(t->next[i]!=NULL) Deletetrie (T-Next[i]); } //Free (T); Delete(T); return 0;}intMain () {Charstr[ -]; inti; for(i=0; i<max; i++) Root->next[i]=NULL; cout<<"Input string 1:"; CIN>>str; Createtrie (str); cout<<"Input string 2:"; CIN>>str; cout<<findtrie (str) <<Endl; return 0;}
Trie Tree (dictionary tree) template