#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHABET_SIZE 26
// Trie node structure
typedef struct TrieNode {
struct TrieNode* children[ALPHABET_SIZE];
int isEndOfWord;
} TrieNode;
// Create a new trie node
TrieNode* getNode() {
TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
node->isEndOfWord = 0;
for (int i = 0; i < ALPHABET_SIZE; i++)
node->children[i] = NULL;
return node;
}
// Insert a word into trie
void insert(TrieNode* root, const char* key) {
TrieNode* curr = root;
for (int i = 0; key[i] != '\0'; i++) {
int index = key[i] - 'a';
if (!curr->children[index])
curr->children[index] = getNode();
curr = curr->children[index];
}
curr->isEndOfWord = 1;
}
// Search prefix in trie, return node at prefix end or NULL
TrieNode* searchPrefix(TrieNode* root, const char* prefix) {
TrieNode* curr = root;
for (int i = 0; prefix[i] != '\0'; i++) {
int index = prefix[i] - 'a';
if (!curr->children[index])
return NULL;
curr = curr->children[index];
}
return curr;
}
// Recursive helper to print all words from given node
void printWords(TrieNode* node, char* buffer, int depth) {
if (node->isEndOfWord) {
buffer[depth] = '\0';
printf("%s\n", buffer);
}
for (int i = 0; i < ALPHABET_SIZE; i++) {
if (node->children[i]) {
buffer[depth] = 'a' + i;
printWords(node->children[i], buffer, depth + 1);
}
}
}
int main() {
TrieNode* root = getNode();
const char* words[] = {"apple", "apart"};
int n = 2;
for (int i = 0; i < n; i++) {
insert(root, words[i]);
}
const char* prefix = "ap";
TrieNode* prefixNode = searchPrefix(root, prefix);
if (prefixNode) {
char buffer[100];
strcpy(buffer, prefix);
printf("Words with prefix '%s':\n", prefix);
printWords(prefixNode, buffer, strlen(prefix));
} else {
printf("No words found with prefix '%s'\n", prefix);
}
return 0;
}
for (int i = 0; key[i] != '\0'; i++) {
iterate over each letter to insert nodes or reuse existing
if (!curr->children[index])
curr->children[index] = getNode();
create new node only if letter path does not exist
curr = curr->children[index];
move current pointer to next letter node
mark end of inserted word
for (int i = 0; prefix[i] != '\0'; i++) {
traverse trie nodes to find prefix end
if (!curr->children[index])
return NULL;
stop if prefix path missing
print word when end of word reached
printWords(node->children[i], buffer, depth + 1);
recursively explore all child nodes to print words
Words with prefix 'ap':
apple
apart