一个Trie树的简单实现

/*trial 树*/
#include 
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;iif(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<std::endl;

    return 0;
}

你可能感兴趣的:(c++)