Trie树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。根节点不包含字符,除根节点外每一个节点都只包含一个字符; 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串; 每个节点的所有子节点包含的字符都不相同。 来源:百度百科
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAX 50
using namespace std;
struct node{
int realnum;
struct node *next[26];
char real[MAX];
};
typedef struct node* myNode;
class Trie{
public:
myNode tree;
Trie()
{
tree=new node;
tree->realnum=0;
for (int i = 0; i<26 ; ++i)
tree->next[i] = NULL;
}
void addnode(char*);
void dfs(myNode);
};
void Trie::addnode(char a[])//添加结点
{
int i,j;
myNode ptr=tree;
for(i=0;a[i]!='\0';++i)
{
if(!ptr->next[a[i]-'a'])
{
ptr->next[a[i]-'a']=new node;
ptr->next[a[i]-'a']-> realnum = 0;
for ( j = 0; j<26 ; ++j)
{
ptr->next[a[i]-'a']->next[j] = NULL;
}
}
ptr =ptr->next[a[i]-'a'];
}
ptr->realnum++;
strcpy(ptr->real,a);
}
void Trie::dfs(myNode ptr)//搜索
{
if(ptr){
if(ptr!=tree&&ptr->realnum !=0)
cout<<ptr->real<<" "<<ptr->realnum <<endl;
for(int i=0;i<26;++i)
dfs(ptr->next[i]);
}
}
int main()
{
Trie WFC;
freopen("圣经.txt","r",stdin);
freopen("result.txt","w",stdout);
char ch,temp;
int tempNum=0;
char str[MAX];
while(cin.get(ch)){
if(ch>='a'&&ch<='z')
temp=ch;
else if(ch>='A'&&ch<='Z')
temp=ch-'A'+'a';
else
{
str[tempNum]='\0';
tempNum=0;
WFC.addnode(str);
continue;
}
str[tempNum++]=temp;
}
WFC.dfs(WFC.tree);
return 0;
}
我作为爱吃紫菜汤的lan小猪,就不一行一行写注释了//
效果如图: