Building Autocomplete

We’re just about ready to build a real autocomplete feature. To make this a tad easier, let’s first build a slightly simpler function that we’ll use to help us with this feature.

Collecting All the Words

The next method we’re going to add to our Trie class is a method that returns an array of all the words in the trie. Now, it’s rare that we’d actually want to list the entire dictionary. However, we’re going to allow this method to accept any node of the trie as an argument so that it can list all the words that start from that node.

The following method, called collectAllWords, collects a list of all the trie’s words starting from a particular node:

 def​ ​collectAllWords​(self, node=None, word=​""​, words=[]):
 # This ...

Get A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.