字典树

字典树又叫trie树,利用字符串的公共前缀来降低查询时间的开销,以及字符串的存储开销。所以经常被搜索引擎系统用于文本词频统计。

字典树的数据结构

#define MAX  26
typedef struct Tree
{
    int count;         //用来标记该节点是个可以形成一个单词,如果count!=0,则从根节点到该节点的路径可以形成一个单词
    struct Tree *child[MAX];
}Node,*Trie_node;

字典树的生成

Node* CreateTrie()                             //创建trie节点树
{
    Node *node=(Node*)malloc(sizeof(Node));
    memset(node,0,sizeof(Node));
    return node;
}
void insert(Trie_node root,char *str)      //trie树插入结点
{
    Node *t=root;
    int len=strlen(str);
   for(int i=0;i<len;i++)
    {
     if(t->child[str[i]-'a']==NULL)
        {
         Node *tmp=(Node*)malloc(sizeof(Node));
           memset(tmp,0,sizeof(Node));
         t->child[str[i]-'a']=tmp;
        }
     t=t->child[str[i]-'a'];

    }
    t->count++;
}

查找该单词是否在字典树中

void search_str(Trie_node root,char *str)             //查找串是否在该trie树中
{
    Node *t=root;
     int len=strlen(str);
   for(int i=0;i<len;i++)
    {
     if(t->child[str[i]-'a']!=NULL)
        {
         t=t->child[str[i]-'a'];

        }
     else
             break;
    }
    if(str[len]=='')
    {
     if(t->count!=0)
            cout<<"该字符串在该trie树中
";
    }
    else
        cout<<"该字符串不在trie树中
";
}

释放空间

void del(Trie_node root)      //释放整个字典树占的堆空间
{
    int i;
    for(i=0;i<MAX;i++)
    {
     if(root->child[i]!=NULL)
            del(root->child[i]);
    }
    free(root);
}
原文地址:https://www.cnblogs.com/wintersong/p/5170109.html