#include<conio.h>
#include<iostream.h>
#include<malloc.h>
#include<string.h>
#define ALPHA 26
#define true 1
#define false 0
#define n 6 //num of rows in input array
struct node
{
int is_end;
int prefix_count;
char ch;
struct node *children[ALPHA];
};
struct node *trie = NULL;
int display(struct node *trie);
struct node *newnode();
int insert(char *s);
int findall(struct node*trie,char *s);
struct node *newnode()
{
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->is_end = 0;
temp->prefix_count = 0;
temp->ch = '0';
for(int i=0;i<ALPHA;i++)
temp->children[i] = NULL;
return temp;
}
int insert(char *s)
{
struct node *head = trie;
if(s==NULL)
return 0;
head->prefix_count++;
int len = strlen(s) , i;
for(i=0;i<len;i++)
{
int letter = (int)s[i] - (int) 'a';
if(head->children[letter]==NULL)
head->children[letter] = newnode();//create the node only if above condition is true else prefix_count has to increase in any case
head->children[letter]->ch = s[i];
head->children[letter]->prefix_count ++;
head= head->children[letter];
}head->is_end = true; //end is reached
}//end of function
int findall(struct node*trie,char *s)
{
int i = 0;
struct node *current = trie;
for(i=0;i<ALPHA;i++)
{
if(current->children[i]!=NULL && current->children[i]->ch==s[i])
current = current->children[i];
}
//I have got the last string matched in cuurent;
int k = current->prefix_count;
cout<<"\n "<<s <<" is a prefix in "<<k<<" number of cases ";
int save = 0;
int flag = 0;
int count = 1;
struct node *ptr;
save = -1;
while(k>0)
{ ptr = current;
flag = 0;
for(i=save + 1;i<ALPHA;i++) //cz if 'd' at save position has been displayed next one should be e
{
if(ptr->is_end==0 && ptr->children[i]!=NULL )
{
if(flag==0)//signal for storing save
{ cout<<"\n ";
save = i;//to save this value of i such that nexttime search begins from i+1 position
flag = 1;
}
cout<<" "<<ptr->children[i]->ch;
ptr = ptr->children[i];
}
if(ptr->is_end==1) //successfully displayed one string
{k--;break;}
}
}
}
int main()
{
char inp[6][15]={"abcde","abcegh","abcpqr","abcxyz","xyz" ,"abcmno"};
int i ;
trie = newnode();
for(i=0;i<n;i++)
insert(inp[i]);
cout<<"\n";
char pre[] = "abc";
findall(trie,pre);
getch();
return 0;
}