A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition
by Jay Wengrow
Trie Insertion
Inserting a new word into a trie is similar to searching for an existing 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.
-
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 we go back to Step 2, moving on to the next character of our search string.
-
If the currentNode does not have a child node that matches the current character, we create such a child node and update the currentNode to be this new node. We then go back to Step 2, moving ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access