字典树,用来统计一篇文章中某个单词出现的次数.比hashmap要节省空间.
我给出的例子,是输入很多个6位数字,统计每个数字出现的次数.因为是0-9个数字,所以next值也就是10.
如果是26个字母,那么next值就是26,以此类推.
字典树的建树方式很简单.
#include "stdafx.h"
using namespace std;
// TODO: 在此处引用程序需要的其他头文件
typedef struct trietree *PTree;
struct trietree{
bool arrive;
int treenum;
PTree next[10];
}node [1000000];
int size;//字典树的大小.
bool findsolve;
int dispose(char *p);
void addnum(int num);
void newtree(int no);
void dfs(char phone[9],int m,PTree p);
int search(int num);
int _tmain(int argc, _TCHAR* argv[])
{
newtree(1);
addnum(333001);
addnum(333001);
addnum(333002);
addnum(333003);
int a = search(333001);
printf("%d",a);
return 0;
}
void newtree(int no){
int i;
node[no].arrive = false;
node[no].treenum = 0;
for(i = 0; i<= 9; i++){
node[no].next[i] = NULL;
}
return;
}
//构造一个字典树
void addnum(int num){
PTree p = &node[1];
int i, k;
for(i = 0; i<= 6; i++){//获取num从低位到高位
k = num%10;
num /= 10;
if(!p ->next[k]){
newtree(++size);
p->next[k] = &node[size];
}
p = p->next[k];
}
p->arrive=true;
p->treenum++;
return;
}
int search(int num){
int i,k;
PTree next;
PTree pre = &node[1];
for(i=0;i<=6;i++){
k = num%10;
num /= 10;
next = pre->next[k];
if(!next){
return 0;
}
pre = next;
}
return pre->treenum;
}