Mark As Completed Discussion

In a trie, deletion refers to removing a word from the trie.

The deletion operation can be done by following these steps:

  1. Start from the root node and initialize a pointer current to track the current node.
  2. Iterate through each character in the word.
  3. Check if the current node contains a link for the character. If not, return false as the word is not present in the trie.
  4. Update the current pointer to the next node.
  5. Repeat steps 3-4 for all characters in the word.
  6. After iterating through all characters, check if the current node is the end of a word. If not, return false as the word is not present in the trie.
  7. Mark the current node as not the end of a word.
  8. Check if the current node has any children. If not, remove the link to the current node from its parent.
  9. Repeat steps 7-8 for all characters in the word, from the last character to the first.

Here is an example implementation of the delete method in the Trie class:

TEXT/X-JAVA
1public void delete(String word) {
2    delete(root, word, 0);
3}
4
5private boolean delete(TrieNode current, String word, int index) {
6    if (index == word.length()) {
7        if (!current.isEndOfWord()) {
8            return false;
9        }
10        current.setEndOfWord(false);
11        return current.getChildren().isEmpty();
12    }
13
14    char ch = word.charAt(index);
15    TrieNode node = current.getChildren().get(ch);
16    if (node == null) {
17        return false;
18    }
19
20    boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
21    if (shouldDeleteCurrentNode) {
22        current.getChildren().remove(ch);
23        return current.getChildren().isEmpty();
24    }
25
26    return false;
27}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment