Hi , I just tried out implementing trie data structure using c , however my first attempt is not much memory efficient .
here is the code
here is the code
#include<stdio.h> #include<stdlib.h> struct node { char data; int final; struct node *next[26]; }; struct node *insert(struct node *root,char *p) { if(root==NULL && *p!='\0') { int i; struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = *p; for(i=0;i<26;i++) { temp->next[i] = NULL; } root = temp; if(*(p+1)!='\0') root->next[*p-97] = insert(root->next[*p-97],++p); } else if(*p!='\0') { if(root->data == *p) root->next[*p-97] = insert(root->next[*p-97],++p); else root->next[*p-97] = insert(root->next[*p-97],p); } return root; } void traversal(struct node *root) { if(root!=NULL) { int i; printf("%c",root->data); for(i=0;i<26;i++) { traversal(root->next[i]); } } } int main() { char *p = "testing"; struct node *root = (struct node *)malloc(sizeof(struct node)); struct node *root1 = (struct node *)malloc(sizeof(struct node)); struct node *root2 = (struct node *)malloc(sizeof(struct node)); root=NULL; root = insert(root," "); root = insert(root,"apple"); root = insert(root,"ant"); root = insert(root,"body"); traversal(root); }