Mark As Completed Discussion

To insert a new word into a trie, we can use the following 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, create a new node and add the character as a link.
  4. Update the current pointer to the newly created node.
  5. Repeat steps 3-4 for all characters in the word.
  6. 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}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment