Understanding Trie Data Structure
Trie, also known as a prefix tree, is a tree-like data structure that proves very efficient for solving problems related to strings. If you’re dealing with scenarios where you have to search for strings, a Trie can be faster than hashing and BSTs.
What is a Trie?
A Trie is a special type of tree used to store associative data structures. Storing strings in a Trie allows us to quickly find words, retrieve them, and prefix them. Each node of the Trie consists of multiple branches, each representing a possible character of keys. We mark the last node of every key as the end of the word node.
Implementing a Trie in Java
Let’s start by creating a TrieNode class:
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isEndOfWord;
TrieNode(){
isEndOfWord = false;
for (int i = 0; i < 26; i++)
children[i] = null;
}
};
In this class, children
is an array storing all child nodes that can be accessed using characters ‘a’-‘z’. isEndOfWord
is a boolean field and is true if the node represents the end of a word.
Insertion in Trie
To insert a key into the Trie, we insert one character at a time. We start from the root, and for…