码迷,mamicode.com
首页 > 其他好文 > 详细

字典树

时间:2018-06-07 20:52:50      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:null   oid   char   int   字符串   malloc   就是   style   root   

字典树类似于二叉树

每一个节点中都有一个指针数组

存的是字符串的一个字符

字典树可以进行查找,统计计数,排序,代码如下

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]);
}

 

字典树

标签:null   oid   char   int   字符串   malloc   就是   style   root   

原文地址:https://www.cnblogs.com/TheQi/p/9152556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!