简体   繁体   中英

Trie Printing in C

I'm having trouble printing out the words of a trie in C. I've implemented the trie like this:

struct trie {

struct trie *children[26];
char letter;
int wordEnd;

};


void printSubtree(struct trie *subtree) {
    int i;  
    if (subtree == NULL){
        return;
    }
    else {
        for (i = 0; i<26;i++) {
            if (subtree->children[i]!= NULL) {
                printf("%c", subtree->children[i]->letter);
                printSubtree( subtree->children[i]);
            }
        }
    }
}

void printResult(){
    struct trie *temp; 
    temp = master;
    int i ;
    if (temp){
        for (i = 0; i<26;i++) {
            if (temp->children[i]!= NULL) {
                printf("%c", temp->children[i]->letter);
                printSubtree(temp->children[i]);
                printf("\n");
                printf("\n");
            } 
        } 
    }   
}

I know this is not right, but I'm not sure how to use recursion to print out words. If the trie has "abc" and "abe" stored as distinct words, what ends up printing out is only the string "abce" , insert of both "abc" and "abe" as different words. Subsequently, I'm unsure how to use DFS to print it out, because wouldn't DFS travel all the way to "abc" , print that out, then go back to the level of "b" , see that "b" has a children that has not been visited, then print it out, resulting in the string "abce" anyway?

A suitable way to print the contents of the trie would be to use a user-defined stack which stores the characters in the path from the root to the current node. On each recursive call, the character contained in the visited note is pushed; on leaving a node, the top of the stack would be popped. Each time a leaf of the trie is reached recursively, the entire stack would be printed. If depth-first search is used without the user-defined stack, the path from the root to the current node is represented only implicitly in the call stack, which cannot be accessed directly.

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