字典树
字典树类似于二叉树
每一个节点中都有一个指针数组
存的是字符串的一个字符
字典树可以进行查找,统计计数,排序,代码如下
typedef struct NODE
{
int nCount;
char szMean[20]; //用来存字符串的,遍历的时候用
struct NODE* pNext[26];
}Tree;
Tree* CreateTree()
{
Tree* ptree = (Tree*)malloc(sizeof(Tree));
memset(ptree->pNext,0,sizeof(Tree*)*26);
memset(ptree->szMean,0,sizeof(char)*20);
ptree->nCount = 0;
return ptree;
}
void InsertNode(Tree* pRoot,char** arr,int length)
{
if(pRoot == NULL || arr == NULL || length <= 0) return ;
Tree* ptemp = NULL;
int i;
for(int j=0;j<length;j++)
{
i=0;
ptemp = pRoot;
//判断字符串到没到结尾
while(arr[j][i] != '\0')
{
//判断根节点中对应的指针数组里有没有值
if(ptemp->pNext[arr[j][i]-97] == NULL)
{
//没有值,创建新的节点
Tree* tree = (Tree*)malloc(sizeof(Tree));
memset(tree->pNext,0,sizeof(Tree*)*26);
memset(tree->szMean,0,sizeof(char)*20);
ptemp->pNext[arr[j][i]-97] = tree;
tree->nCount = 0;
ptemp = tree;
}
else
{
//有值了,往下走
ptemp = ptemp->pNext[arr[j][i]-97];
}
i++;
}
//字符串到结尾了
//把字符串存在结尾的这个数组里
memcpy(ptemp->szMean,arr[j],20);
//结尾的标志++
ptemp->nCount++;
}
}
void Bianli(Tree* tree)
{
if(tree == NULL) return;
// for(int i=0;i<26;i++)
// Bianli(tree->pNext[i]);
//前序遍历,如果注释掉下面就是后序遍历
for(int i=0;i<tree->nCount;i++)
printf("%s\n",tree->szMean);
for(int i=0;i<26;i++)
Bianli(tree->pNext[i]);
}
忘记写查询了....
int Search(Tree* ptree,char* arr)
{
if(arr == NULL|| ptree == NULL) return -1;
int len = strlen(arr);
int i;
for(i=0;i<len;i++)
{
if(ptree->pNext[arr[i]-97] == NULL)
break;
ptree = ptree->pNext[arr[i]-97];
}
if(i != len || ptree->nCount == 0) return -1;
return 1;
}