trie树

View Code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 26

typedef struct Node{
    int isword;
    struct Node *next[MAX];
}Trie;

void InsertTree(Trie *root,const char *s);
int searchTree(Trie *root,const char *s);
void deleteTree(Trie *root);
void InsertTree(Trie *root,const char *s){
    Trie *p=root;
    while(*s!='#'){
        if(p->next[*s-97]!=NULL)
            p=p->next[*s-97];
        else{
            Trie *tmp=(Trie *)malloc(sizeof(Trie));
            p->next[*s-97]=tmp;
            int i=0;
            for(;i<MAX;i++)
                tmp->next[i]=NULL;
            p=p->next[*s-97];
        }
        s++;
    }
    p->isword=1;
}
int  searchTree(Trie *root,const char *s){
    Trie *p=root;
    while(*s!='#'){
        if(p->next[*s-97]){
            p=p->next[*s-97];
            s++;
        }
        else 
            break;
    }
    if(*s=='#')
        return 1;
    return 0;
}
void deleteTree(Trie *root){
    Trie *p=root;
    int i=0;
    for(;i<MAX;i++){
        if(p->next[i]!=NULL){
            deleteTree(p->next[i]);
        }
    }
    free(p);

}

int main(){
    char s[100];
    Trie *root=(Trie *)malloc(sizeof(Trie));
    int i=0;
    for(;i<MAX;i++){
        root->next[i]=NULL;
    }
    int n;
    scanf("%d",&n);
    printf("bulid Tree\n");
    for(i=0;i<n;i++){
        scanf("%s",s);
        s[sizeof(s)]='\0';
        InsertTree(root,s);
    }
    printf("input word you want to search\n");
    scanf("%s",s);
    if(searchTree(root,s)==1){
        printf("yes\n");
    }
    else
        printf("no\n");

    deleteTree(root);

    return 0;
}

Trie树也称字典树,因为其效率很高,所以在在字符串查找、前缀匹配等中应用很广泛,其高效率是以空间为代价的。

一.Trie树的原理

    利用串构建一个字典树,这个字典树保存了串的公共前缀信息,因此可以降低查询操作的复杂度。

字符串"abc","ab","bd","dda",根据该字符串序列构建一棵Trie树。

在该树中,需要8*(26*4+1)=840Byte个字符,如果是普通的形式只需(3+2+2+3)=10Byte个字符。

posted on 2012-06-03 21:49  蓝色守望  阅读(178)  评论(0)    收藏  举报

导航