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 = nullptr;
4  string currentChar = val.substr(0, 1);
5  val = val.substr(1);
6
7  // See how deep we can get in any existing branches
8  while (
9    currentNode->children[currentChar] != NULL &&
10    currentChar.size() > 0
11  ) {
12    currentNode = currentNode->children[currentChar];
13    currentChar = val.substr(0, 1);
14    val = val.substr(1);
15  }
16}