Getting a list of words from a Trie

后端 未结 10 972
野性不改
野性不改 2021-01-02 15:29

I\'m looking to use the following code to not check whether there is a word matching in the Trie but to return a list all words beginning with the prefix inputted by the use

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-02 15:48

    This is easier to solve recursively in my opinion. It would go something like this:

    1. Write a recursive function Print that prints all the nodes in the trie rooted in the node you give as parameter. Wiki tells you how to do this (look at sorting).
    2. Find the last character of your prefix, and the node that is labeled with the character, going down from the root in your trie. Call the Print function with this node as the parameter. Then just make sure you also output the prefix before each word, since this will give you all the words without their prefix.

    If you don't really care about efficiency, you can just run Print with the main root node and only print those words that start with the prefix you're interested in. This is easier to implement but slower.

提交回复
热议问题