Sub topic 7
Deleting Words and Pruning Unused Nodes
This chapter assumes you know the Trie class with insert, search and starts_with from earlier chapters. You should also be comfortable with recursion and with dictionaries as child maps.
Why deletion needs care
Deleting a word from a trie is not the same as deleting a key from a hash set. Words share nodes, so you cannot just remove the path for the word.
Suppose the trie holds car, card and care. Deleting car must keep the nodes for c, a and r, because card and care still use them. Only the end marker on r should change.
Deleting card is different. The node for d is used by no other word, so it should be removed. The node for r stays, because car still ends there.
Three cases
Walk to the last node of the word, then handle one of these cases.
- The word is not in the trie. Change nothing. This includes the case where the path exists but the last node is not an end of a word, such as deleting
cawhen onlycaris stored. - The word's last node has children. Clear
is_endand keep the node. Longer words still depend on it. - The word's last node has no children. Clear
is_end, then remove that node and keep removing ancestors that are now useless.
A node is useless when it has no children and does not mark the end of another word.
The recursive implementation
Pruning happens on the way back up, so recursion fits well. Each call returns a boolean that answers one question for its parent: "Can you delete the link to me?"
def delete(self, word):
def _delete(node, i):
if i == len(word):
if not node.is_end:
return False
node.is_end = False
return not node.children
ch = word[i]
child = node.children.get(ch)
if child is None:
return False
if _delete(child, i + 1):
del node.children[ch]
return not node.is_end and not node.children
return False
_delete(self.root, 0)This method belongs inside the Trie class. Read it in two parts.
The base case runs when i == len(word), so node is the last node of the word. If is_end is false, the word was never stored, and the function returns False. That tells every ancestor to keep its links. Otherwise it clears is_end and returns True only if the node has no children, meaning it can be removed.
The recursive case follows one character. If the child does not exist, the word is absent and nothing changes. If the recursive call returns True, the current node deletes its link to that child. It then returns True itself only when it is not the end of another word and has no remaining children. That condition is what makes pruning continue upward, one node at a time, and stop at the first node that is still needed.
Trying it
t = Trie()
for w in ["car", "card", "care"]:
t.insert(w)
t.delete("card")
print(t.search("card")) # False
print(t.search("car")) # True
print(t.starts_with("car")) # True, because "care" remains
t.delete("care")
t.delete("car")
print(t.starts_with("c")) # False
print(t.root.children) # {}After the last delete, the root has no children. The whole path c-a-r was pruned because no word needed it.
Common errors
- Removing nodes without checking
is_end. If you prune a node only because it has no children, you can delete a node that ends a shorter word. - Clearing
is_endwhen the word is absent. Deletingcamust not change anything when onlycaris stored. The base case guards against this by checkingis_endfirst. - Forgetting to prune. Clearing
is_endalone gives correctsearchresults, but empty branches stay in memory andstarts_withreturnsTruefor prefixes of deleted words. - Deep recursion. The recursion depth equals the word length. For very long keys, an iterative version that records the path on a stack avoids Python's recursion limit.
Exercise
A trie holds "to", "tea" and "ten". You call delete("te"). What does the trie contain afterwards, and does any node get removed?
Show answer
Nothing changes. The path t-e exists, but the node for "e" is not an end of a word, so the base case returns False and no ancestor removes a link. The words "to", "tea" and "ten" are all still stored.
Exercise
A trie holds "to" and "tea". You call delete("tea"). Which nodes are removed, and which stay?
Show answer
The nodes for "a" and "e" are removed, because neither ends another word and neither has other children after the removal. The node for "t" stays, because it still has the child "o". The node for "o" stays and keeps its end marker, so "to" is still found.