I'm trying to print the elements in the trie (function print_trie
), but nothing is displayed in the print statement.
#include <stdio.h>
#include <stdlib.h>
#define CHAR_SIZE 26 // Define the character size
struct Trie {
char data;
int isLeaf; // 1 when the node is a leaf node
struct Trie* character[CHAR_SIZE];
};
struct Trie* getNewTrieNode() {
struct Trie* node = (struct Trie*)malloc(sizeof (struct Trie));
node->isLeaf = 0;
for (int i = 0; i < CHAR_SIZE; i ) {
node->character[i] = NULL;
}
return node;
}
void insert(struct Trie* head, char* str) {
struct Trie* curr = head; // start from the root node
while (*str) {
// create a new node if the path doesn't exist
if (curr->character[*str - 'a'] == NULL) {
curr->character[*str - 'a'] = getNewTrieNode();
}
// go to the next node
curr = curr->character[*str - 'a'];
// move to the next character
str ;
}
curr->isLeaf = 1; // mark the current node as a leaf
}
// Here is the code where I'm not able to print the contents of trie
void print_trie( struct Trie* root) {
if (!root)
return;
struct Trie* temp = root;
for (int i=0; i<CHAR_SIZE; i ) {
if(temp->character[i]!='\0')
printf("%c ",temp->character[i]);
print_trie(temp->character[i]);
}
}
int main() {
struct Trie* head = getNewTrieNode();
char word[10];
printf("\nEnter the word to be inserted: ");
scanf("%s",word);
insert(head,word);
printf("Print the nodes in the trie");
print_trie(head);
return 0;
}
CodePudding user response:
torstenvl already correctly noted that printf("%c ",temp->character[i]);
doesn't work because character[]
is an array of pointers. As each element of that array corresponds to a certain lower case character, you can easily retrieve that character:
printf("%c ", i 'a');
Of course this whole complicated method of storing a string only works as long as the entered string consists of at most nine lower case letters.
CodePudding user response:
struct Trie* character[CHAR_SIZE];
Here character is declared as an array of pointers, not array of characters