A standard trie, also known as a prefix tree, is a hierarchical data structure that stores a dynamic set of strings. Unlike binary search trees, no node in the trie stores the complete key. Instead, a path from the root node to a leaf or a node with a unique value represents a key. Each node in a trie represents a single character from the set of input strings.
struct TrieNode {
struct TrieNode* children[ALPHABET_SIZE];
bool isEndOfWord;
}
//TrieNode Structure: Defines a trie node that has an array of pointers to its children (ALPHABET_SIZE is 26 for lowercase English letters) and a boolean flag isEndOfWord to mark the end of a word.
TrieNode* getNode(void) {
TrieNode* pNode = (TrieNode*)malloc(sizeof(TrieNode));
if (pNode) {
int i;
pNode->isEndOfWord = false;
for (i = 0; i < ALPHABET_SIZE; i++)
pNode->children[i] = NULL;
}
return pNode;
}
//getNode: Dynamically allocates a new trie node and initializes its children to NULL and isEndOfWord to false.
void insert(TrieNode* root, const char* key) {
TrieNode* pCrawl = root;
int index;
int level;
int length = strlen(key);
for (level = 0; level < length; level++) {
index = key[level] - 'a'; // Map the character to an index
if (!pCrawl->children[index])
pCrawl->children[index] = getNode();
pCrawl = pCrawl->children[index];
}
// mark last node as leaf (end of word)
pCrawl->isEndOfWord = true;
}
//insert: Inserts a word into the trie. It calculates the child index for each character (assuming 'a' to 'z') and moves down the trie, creating new nodes as necessary.
bool search(TrieNode* root, const char* key) {
TrieNode* pCrawl = root;
int index;
int level;
int length = strlen(key);
for (level = 0; level < length; level++) {
index = key[level] - 'a';
if (!pCrawl->children[index])
return false;
pCrawl = pCrawl->children[index];
}
return (pCrawl != NULL && pCrawl->isEndOfWord);
}
//search: Searches for a word in the trie. It moves down the trie based on the characters in the word. If it can traverse the trie exactly according to the word and the last node is marked as the end of a word, the word is found.