To insert a new word into a trie, we can use the following 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, create a new node and add the character as a link.
- Update the
current
pointer to the newly created node. - Repeat steps 3-4 for all characters in the word.
- After iterating through all characters, mark the
current
node as the end of a word.
Here is an example implementation of the insert
method in the Trie
class:
TEXT/X-JAVA
1public void insert(String word) {
2 TrieNode current = root;
3
4 for (int i = 0; i < word.length(); i++) {
5 char ch = word.charAt(i);
6
7 if (!current.containsKey(ch)) {
8 current.put(ch, new TrieNode());
9 }
10
11 current = current.get(ch);
12 }
13
14 current.setEnd();
15}
xxxxxxxxxx
25
// Implementing Trie Insertion
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!current.containsKey(ch)) {
current.put(ch, new TrieNode());
}
current = current.get(ch);
}
current.setEnd();
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment