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.ContainsKey(currentChar) &&
10 currentChar.Length > 0
11 ) {
12 currentNode = currentNode.children[currentChar];
13 currentChar = val.Substring(0, 1);
14 val = val.Substring(1);
15 }
16}