trie树—数据结构

来源:互联网 发布:ubuntu如何安装deb软件 编辑:程序博客网 时间:2024/04/28 21:03
首先贴出来引用的两个链接:

http://zh.wikipedia.org/wiki/Trie

http://blog.csdn.net/hackbuteer1/article/details/7964147

trie树又叫字典树,一个典型应用就是搜索提示。本次代码就是这个例子。:)

先贴一个trie树的图



代码如下:


#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>#include<queue>using namespace std;typedef struct  _trieNode{        int count; //统计单词出现的次数        struct _trieNode* next[26] ;        bool exist; //是否出现过该单词}trieNode;int ans = 0;trieNode* createTrieNode(){  trieNode* node = (trieNode*)malloc(sizeof(trieNode));  node->count = 0;  node->exist = false;  memset(node->next,NULL,sizeof(node->next));//0  return node;}void insertTrie(trieNode* root,char w[]){     trieNode* u = root;     for(int i = 0; w[i] != '\0';i++)     {             int n = w[i] - 'a';             if(u->next[n] == NULL)             {               u->next[n] = createTrieNode();             }             u = u->next[n];     }     u->count++;     u->exist = true;}trieNode* searchTrie(trieNode*root,char w[]){   trieNode* u = root;  for(int i = 0; w[i] != '\0'; i++)  {          u = u->next[w[i] - 'a'];  }  return u;}void DFS(trieNode*r,char w[],int pos){     trieNode* u = r;     if(u->exist)     {       printf("%s\n",w);     }     for(int i = 0; i < 26; i++)     {             if(u->next[i] != NULL)             {               w[pos++] = 'a' + i;               w[pos] = '\0';               DFS(u->next[i],w,pos);               pos--;               w[pos] = '\0';             }     }     return ;}int main(){       FILE *fp = fopen("in.txt","r");    char w[15];    char t[15];    trieNode* root = createTrieNode();    while(fscanf(fp,"%s",w) != EOF)    {      //printf("%s\n",w);      insertTrie(root,w);    }    cout<<"请输入你要查询的词:"<<endl;    while(scanf("%s",t) != EOF)    {      DFS(searchTrie(root,t),t,strlen(t));      cout<<"请输入你要查询的词:"<<endl;    }        system("pause");    return 0;}


0 0
原创粉丝点击