[模板]Trie树

来源:互联网 发布:知乎网站 编辑:程序博客网 时间:2024/06/16 00:02

#include <iostream>#include <stdio.h>#include <string.h>using namespace std;const int N = 26;struct Trie{    int num;    bool terminal;    struct Trie *next[N];    Trie()    {        memset(next, NULL, sizeof(next));        num = 0;        terminal = false;    }};Trie* NewTrie(){    Trie *temp = new Trie();    return temp;}void Insert(Trie *root, char *s){    Trie *temp = root;    while(*s)    {        if(temp->next[*s-'a'] == NULL)//不存在,则建立            temp->next[*s-'a'] = NewTrie();        temp = temp->next[*s-'a'];        temp -> num++;        s++;    }    temp -> terminal = true;//到达尾部,标记一个串}bool Search(Trie *root, char *s){    Trie *temp = root;    int sum = 1<<29;    while(*s)    {        if(temp->next[*s-'a'] == NULL)            return false;        temp = temp->next[*s-'a'];        s++;    }    return true;}void DeleteAll(Trie *root)//删除全部节点{    Trie *temp = root;    for(int i=0; i<N; i++)    {        if(temp->next[i] != NULL)            DeleteAll(temp->next[i]);    }    delete temp;}int main(){    Trie *root = NewTrie();    Insert(root, "a");    Insert(root, "abandon");    Insert(root, "abandoned");    if(Search(root, "abc"))        printf("Found!\n");    else        printf("NotFound!\n");    if(Search(root, "ab"))    {        printf("Found!");    }    else        printf("NotFound!\n");    return 0;}





0 0