Trie树的建立与相关操作

先看下JULY大神关于Trie树的介绍 http://blog.csdn.net/v_july_v/article/details/6897097

下面贴上源代码和结果图:

#ifndef TRIE_H_INCLUDED
#define TRIE_H_INCLUDED
#include <vector>
#include <iostream>
#include <cstring>
const int max = 128;    //128个ASCII码

struct TrieNode                     //Trie结点声明
{
    bool isStr;                            //标记该结点处是否构成字符串
    struct TrieNode *child[max];            //孩子分支
    TrieNode(): isStr(false){memset(child,NULL,sizeof(child));}
};

class Trie
{
    public:
        Trie();
        void insert(const char *word);
        bool search(const char *word);
        void printAll();
        void deleteTrie(TrieNode *root);
        ~Trie();
    private:
        TrieNode *root;
        void print(TrieNode *root);
};

Trie::Trie()
{
    root = new TrieNode;
}

void Trie::insert(const char *word)
{
    if(!word || *word == '\0')
    {
        return;
    }
    TrieNode *cur = root;
    const char *begin = word;
    while(*begin)
    {
        if(!(cur->child[*begin]))
        {
            cur->child[*begin] = new TrieNode;
        }
        cur = cur->child[*begin++];
    }
    cur->isStr = true;

}

bool Trie::search(const char *word)
{
    if(!word || *word == '\0')
    {
        return false;
    }
    const char *begin = word;
    TrieNode *cur = root;
    while(*begin)
    {
        if(cur->child[*begin])
        {
            cur = cur->child[*begin++];
        }
        else
        {
            return false;
        }
    }
    return cur->isStr;
}

void Trie::print(TrieNode *root)
{
    static std::vector<char>words;
    if(root->isStr)
    {
        for(std::vector<char>::iterator iter = words.begin(); iter != words.end(); ++iter)
        {
            std::cout<<*iter;
        }
        std::cout<<std::endl;
    }
    for(int i=0; i<max; ++i)
    {
        if(root->child[i])
        {
            words.push_back((char)i);
            print(root->child[i]);
            words.pop_back();
        }
    }
}

void Trie::printAll()
{
    print(root);
}

void Trie::deleteTrie(TrieNode *root)
{
    for(int i=0; i<max; ++i)
    {
        if(root->child[i])
        {
            deleteTrie(root->child[i]);
        }
    }
    delete root;
}

Trie::~Trie()
{
    deleteTrie(root);
}

#endif // TRIE_H_INCLUDED

#include <iostream>
#include "trie.h"
using namespace std;

int main()
{
    Trie trie_tree;
    trie_tree.insert("a");
    trie_tree.insert("ab");
    trie_tree.insert("abc");
    trie_tree.insert("abd");
    trie_tree.insert("bac");
    trie_tree.insert("bad");
    cout<<trie_tree.search("abc")<<endl;
    trie_tree.printAll();
    return 0;
}



结果如下:Trie树的建立与相关操作_第1张图片

你可能感兴趣的:(Trie树的建立与相关操作)