We can use a while
loop to determine the appropriate place to assign our word as a child key in a children
hash. It does this by trying to look for each of our word's characters in the current node's children
hash, and if there's a match, we try to place it in the next child's children
hash. This handles the case where lineages like c -> a -> t
in "category"
may have already been previously added with a word like "cater"
.
1void add(String val) {
2 Node currentNode = this.head;
3 Node newNode = null;
4 String currentChar = val.substring(0, 1);
5 val = val.substring(1);
6
7 // See how deep we can get in any existing branches
8 while (
9 currentNode.children.get(currentChar) != null &&
10 currentChar.length() > 0
11 ) {
12 currentNode = currentNode.children.get(currentChar);
13 currentChar = val.substring(0, 1);
14 val = val.substring(1);
15 }
16}