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.

1def add(self, key):
2  # add key into trie if not present
3  # else just marks the leaf node
4  pCrawl = self.root
5  length = len(key)
6  for level in range(length):
7      index = self._charToIndex(key[level])
8      if not pCrawl.children[index]:
9          pCrawl.children[index] = TrieNode()
10      pCrawl = pCrawl.children[index]
11
12      # mark last node as leaf
13  pCrawl.isEndOfWord = True