-2

I am working on code that will print out the words contained in a trie and note the amount of times that the word occurred. I thought the most effective way would be for a letter to be stored in the element of the relevant node when a word is added to the trie. Occurrences is basically a flag to signal the end of a word, and is incremented if it is the last letter of a word (indicating the word count).

My struggle at this point is how to get the loop to check all of the children of a node, rather than in a straight line as it is doing right now, but I can't visualize how it would work. Ideas?

struct Node{
    char letter;
    struct Node children[26];
    int occurences;
};

printTrie(struct node root){
    int i = 1;
    while(root[i] != NULL){
        fprint(root.letter);
        printTrie(root->children[]);
    }
    i++;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Brooklyn
  • 17
  • 1
  • 7
  • 2
    That isn't valid C code. `root[i]` isn't valid for `root` that is a `struct` *anything*, much less a mysterious `struct node`, which is not provided in your code list. Post *real* code, *please*. – WhozCraig Nov 09 '17 at 01:09
  • 2
    This looks like you're missing a number of asterisks `*` indicating pointers. You can't have an array of `struct Node` inside a `struct Node`; the universe isn't big enough to hold the structure. You can have an array of `struct Node *` (pointers to `struct Node`). You function call should probably be taking a `struct Node *root` too — it currently takes a `struct node` by value, but you've not shown what a `struct node` looks like, beyond it is unrelated to the `struct Node` that you show (C is a case-sensitive language). – Jonathan Leffler Nov 09 '17 at 01:59

1 Answers1

0

The word you are looking for is recursion, here is how you do it:

if(root != NULL) {
    printf("%c\n", &root->letter);
    printf("%d\n", &root->occurences);
    int i;
    for (i = 0; i < 26; i++) {
        printTrie(root->children[i]); /* <-- Recursion */
    }
}

Right now, it will print the value of the root first, then the value of each child.

If you want it to print the value of each child before the root, move the printf to be after the for-loop

smac89
  • 39,374
  • 15
  • 132
  • 179