Deletion in a Trie
After insertion and search, let's figure out the logic behind deletion in tries.
Deleting a Word in a Trie
While deleting a node, we need to make sure that the node we are trying to delete does not have any further child branches. If there are no branches, we can easily remove the node.
However, if the node contains child branches, this opens up a few scenarios which we will cover below.
Case 1: Word with No Suffix or Prefix
If the word to be deleted has no suffix or prefix and all the character nodes of this word have no children, then we will delete all nodes up to the root.
However, if any of these nodes have other children (are part of another branch), then they will not be deleted. This will be explained further in Case 2.
In the figure below, the deletion of the word bat would mean that we have to delete all characters of bat.
Case 2: Word is a Prefix
If the word to be deleted is a prefix of some other word, then the value of isEndWord of the last node of that word is set to false and no node is deleted.
For example, to delete the word the, we will simply unmark ...