In a trie, deletion refers to removing a word from the trie.
The deletion operation can be done by following these steps:
- Start from the root node and initialize a pointer
current
to track the current node. - Iterate through each character in the word.
- Check if the current node contains a link for the character. If not, return false as the word is not present in the trie.
- Update the
current
pointer to the next node. - Repeat steps 3-4 for all characters in the word.
- 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. - Mark the
current
node as not the end of a word. - Check if the
current
node has any children. If not, remove the link to thecurrent
node from its parent. - 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}
xxxxxxxxxx
73
}
class TrieNode {
private Map<Character, TrieNode> children;
private boolean isEndOfWord;
public TrieNode() {
children = new HashMap<>();
isEndOfWord = false;
}
public Map<Character, TrieNode> getChildren() {
return children;
}
public boolean isEndOfWord() {
return isEndOfWord;
}
public void setEndOfWord(boolean endOfWord) {
isEndOfWord = endOfWord;
}
}
class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment