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.
1func (t *trie) add(val string) {
2 currentNode := t.root
3 var newNode *node
4 currentChar := val[0:1]
5 val = val[1:]
6
7 // See how deep we can get in any existing branches
8 for currentNode.children[currentChar] != nil && len(currentChar) > 0 {
9 currentNode = currentNode.children[currentChar]
10 currentChar = val[0:1]
11 val = val[1:]
12 }
13
14 // Split each character into levels respectively
15 // 'val' is the character, and 'value' lets us know if it terminates
16 for len(currentChar) != 0 {
17 newNode = &node{
18 val: currentChar,
19 children: make(map[string]*node),
20 }
21
22 if len(val) == 0 {
23 newNode.value = nil
24 }
25
26 currentNode.children[currentChar] = newNode
27
28 currentNode = newNode
29 currentChar = val[0:1]
30 val = val[1:]
31 }
32}