一个Trie树的简单实现

/*trial 树*/
#include <iostream>
const int branchNum=26;//英文单词的基为26个英文字母

struct Trie_Node
{
    bool is_Str;
    Trie_Node *next[branchNum];
    Trie_Node() : is_Str(false) {memset(next,0,sizeof(next));}

};

class Trie
{
public:
    Trie() {root=new Trie_Node();}
    void insert(const char* word);
    bool search(const char* word);
    void deleteTrie(Trie_Node *root);
    Trie_Node * getTrie() {return root;}
    /* data */
private:
    Trie_Node *root;
};

void Trie::insert(const char* word)
{
    Trie_Node *location=root;

    while(*word)
    {
        if(location->next[*word-'a']==NULL)
        {
            Trie_Node *tmp=new Trie_Node();
            location->next[*word-'a']=tmp;
        }
        location=location->next[*word-'a'];
        word++;
    }
    location->is_Str=true;
}

bool Trie::search(const char* word)
{
    Trie_Node *location=root;
    while(*word && location)
    {
        location=location->next[*word-'a'];
        word++;
    }
    return (location!=NULL && location->is_Str);
}

void Trie::deleteTrie(Trie_Node *root)
{
    for(int i=0;i<branchNum;i++)
        if(root->next[i]!=NULL)
            deleteTrie(root->next[i]);
    delete root;
}


int main(int argc, char const *argv[])
{

    Trie trie_tree;
    trie_tree.insert("cai");
    trie_tree.insert("cao");
    trie_tree.insert("li");
    trie_tree.insert("lan");
    bool flag = trie_tree.search("la");
    std::cout<<flag<<std::endl;

    return 0;
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/xiaolewennofollow/article/details/50898224
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞