Trie is a tree-based data structure used for efficient retrieval of a key in a huge word set. In this post, we will implement the Trie data structure in Java.

In the previous post, we discussed a Trie data structure in detail and covered its C implementation. In this post, the Trie data structure’s Java implementation is discussed, which is way cleaner than the C implementation.

 
Following is the Java implementation of the Trie data structure, which supports insertion and search operations. The implementation currently supports only lowercase English characters (a – z), but we can easily extend the solution to support any set of characters.

Download  Run Code

 
The space complexity of a Trie data structure is O(N × M × C), where N is the total number of strings, M is the maximum length of the string, and C is the alphabet’s size.

The storage problem can be alleviated if we only allocate memory for alphabets in use and don’t waste space storing null pointers. Following is a memory-efficient implementation of Trie data structure in Java, which uses HashMap to store a node’s children:

Download  Run Code

 
Also see:

C++ Implementation of Trie Data Structure

Trie Data Structure – Python Implementation