Trie[字典树] 数据结构及基本操作集

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define Max 26
typedef struct TrieNode *Trie;
struct TrieNode
{
    Trie next[Max];
    int num;
    TrieNode()
    {
        for (int i = 0; i < Max; i++)
            next[i] = NULL;
        num = 0;
    }
};


void Insert(Trie root,char *s)
{
    Trie p = root;
    for (int i = 0; s[i]; i++) {
        int t = s[i]-'a';
        if (p->next[t] == NULL)
            p->next[t] = new TrieNode;
        p = p->next[t];
    }
    p->num++;
}

void Delete(Trie root, char *s)
{
    int len = strlen(s);
    Trie p = root;
    for (int i = 0; i < len; i++) {
        int t = s[i]-'a';
        if (p->next[t] == NULL)
            return;
        p = p->next[t];
    }
    p->num--;
}

bool Search(Trie root, char *s)
{
    Trie p = root;
    if (p == NULL)
        return 0;
    int len = strlen(s);
    for (int i = 0; i < len; i++) {
        int t = s[i]-'a';
        if (p->next[t] == NULL)
            return 0;
        p = p->next[t];
    }
    return p->num > 0;
}

void PrintDic(Trie root, vector<vector<char> > &words, vector<char> &word)
{
    if (root == NULL)
        return;
    if (root->num > 0)
        words.push_back(word);
    for (int i = 0; i < Max; i++) {
        if (root->next[i]) {
            word.push_back('a'+i);
            PrintDic(root->next[i], words, word);
            word.pop_back();
        }
    }
}

void FreeTrie(Trie root)
{
    for (int i = 0; i < Max; i++) {
        if (root->next[i] != NULL)
            FreeTrie(root->next[i]);
    }
    delete root;
}

int main()
{
    freopen("1.txt", "r", stdin);
    Trie root = new TrieNode;
    char s[300];
    while (cin >> s) {
        Insert(root, s);
    }
    //char temp[50] = "avvvvefaf";
    //cout << Search(root, temp);
    //Delete(root, temp);
    //cout << Search(root, temp);

    vector<char> word;
    vector<vector<char> >words;
    PrintDic(root, words, word);
    for (int i = 0; i < words.size(); i++) {
        for (int j = 0; j < words[i].size(); j++) {
            printf("%c", words[i][j]);
        }
        printf("
");
    }



    return 0;
}
原文地址:https://www.cnblogs.com/whileskies/p/7273528.html