1. Introduction
A Trie, also known as a prefix tree, is a tree-like data structure that is used to store a dynamic set of strings. Tries are particularly useful for searches in dictionaries with a large number of words. Each node of a Trie has multiple branches, each representing a possible character of strings. The key advantages of a Trie include the ability to quickly search for, insert, and delete strings.
2. Program Steps
1. Define the structure of a Trie node.
2. Implement methods to insert, search, and delete strings from the Trie.
3. Code Program
// Class to represent a Trie node
class TrieNode {
final int ALPHABET_SIZE = 26;
TrieNode[] children = new TrieNode[ALPHABET_SIZE];
boolean isEndOfWord;
TrieNode() {
isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++) {
children[i] = null;
}
}
}
public class Trie {
private TrieNode root;
Trie() {
root = new TrieNode();
}
// Method to insert a string into the Trie
public void insert(String key) {
TrieNode node = root;
for (int level = 0; level < key.length(); level++) {
int index = key.charAt(level) - 'a';
if (node.children[index] == null)
node.children[index] = new TrieNode();
node = node.children[index];
}
node.isEndOfWord = true;
}
// Method to search for a string in the Trie
public boolean search(String key) {
TrieNode node = root;
for (int level = 0; level < key.length(); level++) {
int index = key.charAt(level) - 'a';
if (node.children[index] == null)
return false;
node = node.children[index];
}
return (node != null && node.isEndOfWord);
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("hello");
trie.insert("world");
System.out.println(trie.search("hello")); // true
System.out.println(trie.search("hell")); // false
}
}
Output:
true false
4. Step By Step Explanation
1. The TrieNode class represents a single node of the Trie. Each node has an array of children, each representing a possible character in the alphabet. The isEndOfWord attribute indicates whether the node marks the end of a word.
2. The Trie class encapsulates the Trie operations.
3. The insert method is used to insert a word into the Trie. We traverse the Trie node by node, character by character from the word, and create nodes as necessary.
4. The search method is used to check if a word is present in the Trie. Like the insert operation, we traverse the Trie character by character from the word, but if at any point the character doesn't have a corresponding node, we return false.
5. In the main method, we demonstrate the usage of the Trie by inserting two words "hello" and "world" and then searching for them. The output confirms that "hello" is present while "hell" is not.