Next we'll use a while
loop to iterate through each letter of the word, and create nodes for each of the children and attach them to the appropriate key. Depending on the language, there may be a more efficient implementation where the lookup and initialization happen simultaneously.
1void add(String val) {
2 TrieNode currentNode = this.getRoot();
3 TrieNode newNode;
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.getChildren().containsKey(currentChar) &&
10 currentChar.length() > 0
11 ) {
12 currentNode = currentNode.getChildren().get(currentChar);
13 currentChar = val.substring(0, 1);
14 val = val.substring(1);
15 }
16
17 // Break each character into levels respectively
18 // 'val' is the character, and 'value' lets us know if it terminates
19 while (currentChar.length() != 0) {
20 newNode = new TrieNode();
21 newNode.setVal(currentChar);
22 newNode.setValue(val.length() == 0 ? null : undefined);
23 newNode.setChildren(new HashMap<>());
24
25 currentNode.getChildren().put(currentChar, newNode);
26 currentNode = newNode;
27 currentChar = val.substring(0, 1);
28 val = val.substring(1);
29 }
30}