字典树模板

我的字典树模板


#define
MAXNUM 26 //定义字典树结构体 typedef struct Trie { bool flag;//从根到此是否为一个单词 Trie *next[MAXNUM]; }Trie; //声明一个根 Trie *root; //初始化该根 void init() { root = (Trie *)malloc(sizeof(Trie)); root->flag=false; for(int i=0;i<MAXNUM;i++) root->next[i]=NULL; } //对该字典树的插入单词操作 void insert(char *word) { Trie *tem = root; while(*word!='\0') { if(tem->next[*word-'a']==NULL) { Trie *cur = (Trie *)malloc(sizeof(Trie)); for(int i=0;i<MAXNUM;i++) cur->next[i]=NULL; cur->flag=false; tem->next[*word-'a']=cur; } tem = tem->next[*word-'a']; word++; } tem->flag=true; } //查询一个单词的操作 bool search(char *word) { Trie *tem = root; for(int i=0;word[i]!='\0';i++) { if(tem==NULL||tem->next[word[i]-'a']==NULL) return false; tem=tem->next[word[i]-'a']; } return tem->flag; } //释放字典树内存操作,由于本题测试数据后程序自动跳出,所以这里没写释放内存函数 void del(Trie *cur) { for(int i=0;i<MAXNUM;i++) { if(cur->next[i]!=NULL) del(cur->next[i]); } free(cur); }

关于字典树具体可参考百度百科解释  字典树   这里不做过多解释,模板稍作改变即可用来解决这类通用问题。

原文地址:https://www.cnblogs.com/newpanderking/p/2752628.html