trie树—数据结构

首先贴出来引用的两个链接:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值