Observing the above, you'll note that each path from the root to a leaf constitutes a string. Most nodes, except for the last, have a character value (except for the leaves which indicate the end, letting us know it's a word). So what we'd want to do in the following methods is:
add - create nodes and place them in the right place
search - traverse through nodes until you find possible words
remove - delete all associated nodes
Let's start by defining the class constructor. We'll start with just the head node, which will have a val
property of an empty string (since it's only the root and can branch off to any letter), and an empty children object
which we'll populate with add
.
xxxxxxxxxx
class Trie {
constructor() {
this.head = {
val: '',
children: {}
};
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment