简体   繁体   中英

Printing the words of a trie tree

I was trying to print the contents of a trie in C. However I'm not very sucessful. And also let me say right in the beginning that this something we are doing in school right now, and this is one exercise.

This is how my trie looks like:

struct node{
    char letter; //holds the letter associated with that node
    int count; //its count
    struct node* child[26]; //each node can have 26 children
};

struct trie{
    struct node* root;
};

This print method has to traverse this trie and print the words in alphabetic order and the ones that have a count of 0 should not be printed.

I was thinking along recursion and this is what my code looks like:

void print(node* root) {
    char buffer[15];//array to store the letters
    if(root==NULL){ return;}//if the root is null return
    int i;
    int index=0; //index for the buffer
    int hasAChild=hasChild(root);

    if (hasAChild != 0) { //the root has children keep on going
        for (i=0;i<27;i++) {
            //go thru all the children and if they have children call print                         recursively
            if (hasChild(root->child[i])) {
                print(root->child[i]);
            }
            else {
                // if they have no more children add the letter to the buffer
                buffer[index++] = root->child[i]->letter;
            }
            // print the contents in the bufffer
            printf("%s: %d",root->child[i]->count);
        }
    }
}

// function to determine if a node has children, if so it returns their number if not,returns 0

int hasChild(root) {
    if(root==NULL){
        return 0;
    }

    int i;
    int count=0;
    for(i=0;i<27;i++){
        if(root->child[i]!=NULL){
            count++;
        }
    }
    return count;
}

This is what it would look like

Example of a trie:

Root
  +--- a:2
  |     +--- t:4
  |
  +--- b:3
  |     +--- e:5
  |
  +--- c:0

we have 'a' 2 times, 'at' 4 times, 'b' 3 times and 'be' 5 times, only the words should be printed. In this example I will have to print at: 4 be: 5 but not c: 0 since its count is 0

So i'm only suppose to print the words that are formed, not the letters that do not form a word. Any help or guidance would be greatly appreciated. Thank you!

I see three issues here:

  • you append a letter to the current buffer only when the current node has no children. This means that you will only display the last letter of the words.

  • in addition, every time you enter the function, you start with an empty buffer.

  • your printf statement is missing a string argument.

You need to pass the length and the buffer, and make sure to null-terminate it correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM