Wanted to write a program to implement a dictionary of words using Tries Data Structure.
Please tell me the structure for the implementation so that I could start the program, as i haven’t got any article on internet, for Tries Implementation..
The confusion is, that when we search through the word, and we get through the word at the leaf node, only then is the meaning of the word would be stored.. But all the nodes in Tries data structure will be of waste. i.e. storing a variable of meaning in every internal node……
So, the basic idea, is with a help of small example as how to store dictionary, please let me know the structure for Tries Data Structure..
And please C program Implementation..
Thanks..
Compressed Tries.. This is giving me the correct Compressed Trie, as expected,,,, but there are some issues with it…. And wanted to discuss that….
1) I Build a simple trie first, and then compressed it using a function trie_compress(), Now when i want to add any word into it, it would want a changed trie_add(), also changed trie_lookup(), ok i will do this on my own, just wanted to know, is my approach correct or there could be some better way..
2) In trie_new(), I have used t->substr = (char*)malloc(10);,,,,,, This doesn’t look efficient, as memory should be allocated, as in when required. Can we improve upon this.
typedef struct trie
{
int on;
char *substr;
struct trie *first_child;
struct trie *next_sibling;
}trie;
trie* trie_new()
{
trie *t = (trie*)malloc(sizeof(trie));
t->substr = (char*)malloc(10);
t->on = 0;
t->substr[0] = '\0';
t->first_child = NULL;
t->next_sibling = NULL;
return t;
}
trie* trie_at_level(trie *t, char c)
{
while(t != NULL)
{
if(t->substr[0] == c)
{
return t;
}
t = t->next_sibling;
}
return NULL;
}
void trie_add(trie *t, const char *str)
{
const int n = strlen(str);
int i;
for(i=0; i<n; i++)
{
const char c = str[i];
trie* parent = t;
t = t->first_child;
t = trie_at_level(t,c);
if(t == NULL)
{
t = trie_new();
t->substr[0] = c;
t->substr[1] = '\0';
t->next_sibling = parent->first_child;
parent->first_child = t;
}
}
t->on = 1;
}
int trie_lookup(trie *t, const char *str)
{
const int n = strlen(str);
int i;
for(i=0; i<n; i++)
{
const char c = str[i];
t = t->first_child;
t = trie_at_level(t,c);
if(t == NULL)
return 0;
}
return t->on;
}
void trie_compress(trie *t)
{
trie* parent = t;
t = t->first_child;
if(t->first_child != NULL)
trie_compress(t);
if(t->next_sibling == NULL)
{
parent->substr = strcat(parent->substr,t->substr);
parent->first_child = t->first_child;
parent->on = t->first_child->on;
free(t);
return;
}
else
trie_compress(t->next_sibling);
}
Okay, I think I got it right this time around.
Compressed Trie: