To insert a new word into a trie, we can use the following steps:
- Start from the root node and initialize a pointer
currentto 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
currentpointer to the newly created node. - Repeat steps 3-4 for all characters in the word.
- After iterating through all characters, mark the
currentnode 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}xxxxxxxxxx25
// Implementing Trie Insertionpublic 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



