Trie樹

Trie樹也稱字典樹,由於其效率很高,因此在在字符串查找、前綴匹配等中應用很普遍,其高效率是以空間爲代價的。利用串構建一個字典樹,這個字典樹保存了串的公共前綴信息,所以能夠下降查詢操做的複雜度。spa

下面以單詞爲例,插入、查找和刪除實現code

#define MaxN 26
typedef struct TrieNode
{
    bool isStr; //標記是否構成單詞
    struct TrieNode *next[MaxN];
}Trie;

void InsertWords(Trie *root, const char *s)
{
    if(root == NULL || *s == '\0')
        return;
    Trie *p = root;
    while(*s != '\0')
    {
        if(p->next[*s-'a']==NULL)
        {
            Trie *temp = new Trie();
            for(int i = 0; i< MaxN; i++)
            {
                temp->next[i] = NULL;
            }
            temp->isStr = false;
            p->next[*s-'a'] = temp;
            p = p->next[*s-'a'];
        }
        else
        {
            p = p->next[*s-'a'];
        }
        s++;
    }
    p->isStr = true;
}

int SearchWord(Trie *root, const char *s)
{
    Trie *p = root;
    while(p != NULL && *s != '\0')
    {
        p = p->next[*s-'a'];
        s++;
    }
    return (p != NULL && p->isStr == true);
}

void delTrie(Trie *root)
{
    for(int i = 0; i < MaxN; i++)
    {
        if(root->next[i] != NULL)
            delTrie(root->next[i]);
    }
    delete root;
}
相關文章
相關標籤/搜索