字典树实例

来源:互联网 发布:孙子定理c语言代码 编辑:程序博客网 时间:2024/06/05 07:33

字典树

 
又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
一下是示例代码
#include <stdio.h>
#include <malloc.h>
#define MAX 26
typedef struct __trie{
    struct __trie* nodes[MAX];
    char c;
    char count;
    void* payload;
    struct __trie* parent;
}  Trie;
Trie* trie_new_node(void* payload)
{
    Trie* p = (Trie*)malloc(sizeof(Trie));
    if(NULL == p)
    {
        return NULL;
    }
    int i = 0;
    for(/* void */;i<MAX;i++)
    {
        p->nodes[i] = NULL;
    }
    p->c = 0;
    p->count = 0;
    p->payload = payload;
    p->parent = NULL;
    return p;
}
int trie_insert(Trie* t,char* str,void* payload)
{
    char c = *str;
    if(c == 0)
    {
        t->payload = payload;
        t->count = 1;
        return 0;
    }
    if(c > 'z' || c < 'a')
    {
        return -1;
    }
    int index = c - 'a';
    if(t->nodes[index] == NULL)
    {
        t->nodes[index] = trie_new_node(NULL);
        t->nodes[index]->c = c;
        t->nodes[index]->parent = t;
    }
    return trie_insert(t->nodes[index],++str,payload);
}
int trie_update(Trie* t,char* str,void* payload)
{
    return trie_insert(t,str,payload);
}
Trie* trie_find(Trie* t,char* str)
{
    if(*str == 0){
        if(t->count == 1)
        {
            return t;
        }
        return NULL;
    }
    int index = *str - 'a';
    if(t->nodes[index] ==  NULL)
    {
        return NULL;
    }
    return trie_find(t->nodes[index],++str);
}
void trie_delete(Trie* t,char* str){
    if(*str == 0){
        t->count = 0;
        return ;
    }
    int index = *str - 'a';
    Trie* node = t->nodes[index];
    if(node ==  NULL)
    {
        return ;
    }
    trie_delete(node,++str);
    int del = 1;
    int i;
    for(i=0;i<MAX;i++){
        if(node->nodes[i] != NULL){
            del = 0;
            break;
        }
    }
    if(del == 1 && node->count == 0){
        node->parent->nodes[node->c-'a'] = NULL;
        free(node);
    }
}
void trie_list(Trie* t,void(*handle)(void*)){
    if(t->count != 0){
        handle(t->payload);
    }
    int i=0;
    for(/*void*/;i<MAX;i++)
    {
        if(t->nodes[i] != NULL){
            printf("not empty\n");
            trie_list(t->nodes[i],handle);
        }
    }
}
int main(void)
{
    Trie* root = trie_new_node(NULL);
    trie_insert(root,"a","a\n");
    trie_insert(root,"abc","abc\n");
    trie_insert(root,"abcd","abcd\n");
    trie_list(root,printf);
    printf("\n\n\n\n\n");
    trie_delete(root,"abcd");
    trie_delete(root,"a");
    trie_list(root,printf);
    return 0;
}

0 0
原创粉丝点击