📜  trie tableau c (1)

📅  最后修改于: 2023-12-03 15:05:37.766000             🧑  作者: Mango

Trie Tableau in C

Introduction

Trie Tableau is a data structure that combines the properties of both trie and hash table. It is an array of pointers where each pointer points to another array of pointers until a leaf node is reached. It is a tree-like structure where each level describes a character of the string.

In C, Trie Tableau is implemented using an array of pointers where the index of each pointer represents the ASCII value of the character. The value of the pointer may either be a NULL pointer or another array of pointers corresponding to the next level.

Trie Tableau is commonly used to store a large number of strings and is used in applications such as dictionary, autocomplete, and text search.

Implementation
Data Structure

The Trie Tableau is implemented using a TrieNode struct which contains an array of pointers to the next level of TrieNodes, a flag to indicate the end of a string, and a count field to keep track of the frequency of a string.

struct TrieNode {
    struct TrieNode* children[256];
    int count;
    bool isEndOfWord;
};
Insertion

Insertion in Trie Tableau is done recursively. To insert a string, we start from the root and traverse through the trie. If a given character is not present in the trie, we create a new TrieNode and add it to the current node's children array at the index corresponding to the character's ASCII value. If the node already exists, we simply move to the node corresponding to the next character.

void insert(struct TrieNode* root, char* key) {
    struct TrieNode* node = root;
    for (int i = 0; i < strlen(key); i++) {
        int index = key[i];
        if (node->children[index] == NULL) {
            node->children[index] = createTrieNode();
        }
        node = node->children[index];
    }
    node->count++;
    node->isEndOfWord = true;
}
Search

Searching in Trie Tableau is similar to insertion. We traverse through the trie, but this time we check if each character exists in the trie. If we reach a NULL pointer, we know that the string is not present in the trie. If we reach the end of the string, we check if the current node flag is true, indicating the end of the string.

bool search(struct TrieNode* root, char* key) {
    struct TrieNode* node = root;
    for (int i = 0; i < strlen(key); i++) {
        int index = key[i];
        if (node->children[index] == NULL)
            return false;
        node = node->children[index];
    }
    return (node != NULL && node->isEndOfWord);
}
Conclusion

Trie Tableau is a versatile data structure for storing and searching large volumes of strings. By combining the properties of both trie and hash table, it provides a fast and efficient way of searching through a large dataset. Although it requires more memory than a traditional trie, it provides faster search times and reduces the number of cache misses.