Trie Insertion
Inserting a new word into a trie is similar to searching for an existing word. We first search to see if the word already exists in the trie. If it doesn’t, we insert the new word.
Here’s how the algorithm goes:
-
We establish a variable called currentNode. At the beginning of our algorithm, this points to the root node.
-
We iterate over each character of our search string. Here, our search string represents the new word we’re inserting. We call it a search string since we’re also searching whether the string already exists in the trie.
-
As we point to each character of our search string, we look to see if the currentNode has a child with that character as a key.
-
If it does, we update the currentNode to become that child node, and ...
Get A Common-Sense Guide to Data Structures and Algorithms in JavaScript, Volume 1 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.