#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define ALPHABET_SIZE 26
// Trie node structure
typedef struct TrieNode {
struct TrieNode* children[ALPHABET_SIZE];
bool isEndOfWord;
} TrieNode;
// Create a new trie node
TrieNode* getNode() {
TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
node->isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
node->children[i] = NULL;
return node;
}
// Insert a word into the trie
void insert(TrieNode* root, const char* word) {
TrieNode* curr = root;
for (int i = 0; word[i] != '\0'; i++) {
int index = word[i] - 'a';
if (curr->children[index] == NULL) {
curr->children[index] = getNode();
}
curr = curr->children[index]; // advance curr to next node
}
curr->isEndOfWord = true; // mark end of word
}
// Recursive helper to print all words from given node
void printWordsFromNode(TrieNode* node, char* prefix, int length) {
if (node->isEndOfWord) {
prefix[length] = '\0';
printf("%s\n", prefix); // print found word
}
for (int i = 0; i < ALPHABET_SIZE; i++) {
if (node->children[i] != NULL) {
prefix[length] = 'a' + i;
printWordsFromNode(node->children[i], prefix, length + 1); // recurse deeper
}
}
}
// Search for prefix node in trie
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] == NULL) {
return NULL; // prefix not found
}
curr = curr->children[index]; // advance curr
}
return curr; // node representing prefix
}
int main() {
TrieNode* root = getNode();
insert(root, "apple");
insert(root, "app");
insert(root, "apply");
const char* prefix = "app";
TrieNode* prefixNode = searchPrefix(root, prefix);
if (prefixNode == NULL) {
printf("No words found with prefix '%s'\n", prefix);
} else {
char buffer[100];
strcpy(buffer, prefix);
printWordsFromNode(prefixNode, buffer, strlen(prefix));
}
return 0;
}
curr = curr->children[index]; // advance curr to next node
advance curr pointer to next letter node to build or search word
curr->isEndOfWord = true; // mark end of word
mark current node as end of a complete word
if (node->isEndOfWord) { prefix[length] = '\0'; printf("%s\n", prefix); }
print word when end of word node is reached during traversal
if (curr->children[index] == NULL) { return NULL; }
stop search if prefix letter path does not exist
printWordsFromNode(prefixNode, buffer, strlen(prefix));
start collecting and printing all words under prefix node