Deletion is trickier than insertion. You can't remove nodes—other words might share the path.
Simple approach: set isEndOfWord = false:
def delete(word):
node = findNode(word)
if node:
node.isEndOfWord = false
This wastes space but is simple. The "deleted" word won't be found by search, but the nodes remain.
Full deletion requires checking if nodes are safe to remove:
def delete(word):
def deleteHelper(node, word, depth):
if depth == len(word):
node.isEndOfWord = false
return len(node.children) == 0
char = word[depth]
if deleteHelper(node.children[char], word, depth + 1):
del node.children[char]
return len(node.children) == 0 and not node.isEndOfWord
return false
deleteHelper(root, word, 0)
Remove nodes bottom-up only if they have no children and aren't word endings.