How to implement a Trie data structure in Java?
Jul 13, 2025 am 01:16 AMThe core of implementing the Trie tree is to design the node structure and correctly handle the insertion and search logic. 1. The TrieNode class contains a character array or hash table to indicate whether the child nodes and markers are endings; 2. Insert operation to build a character-by-character path and mark the end of the word at the end; 3. The search operation is divided into two situations: complete word matching and prefix matching; 4. It is necessary to consider edge cases such as empty strings, case sensitivity, memory optimization, etc. and improvement directions.
Implementing a trie (prefix tree) in Java is a common task when dealing with problems related to string searching, autocomplete features, or dictionary implementations. The core idea behind a trie is that each node represents a character, and paths from the root to nodes represent possible strings.

Basic Structure of a Trie Node
To start building a trie, you first need a TrieNode
class. This class will represent each character in the trie and contain:
- An array or map of children (dependent on whether you're using a fixed alphabet like lowercase English letters or a more general approach).
- A flag to indicate if the node marks the end of a word.
class TrieNode { private TrieNode[] children; private boolean isEndOfWord; private static final int ALPHABET_SIZE = 26; // assuming only lowercase English letters public TrieNode() { children = new TrieNode[ALPHABET_SIZE]; isEndOfWord = false; } public TrieNode getChild(char ch) { return children[ch - 'a']; } public void setChild(char ch, TrieNode node) { children[ch - 'a'] = node; } public boolean isEndOfWord() { return isEndOfWord; } public void setEndOfWord(boolean endOfWord) { isEndOfWord = endOfWord; } }
Using an array here makes looksups faster since we can directly index into the correct position using ch - 'a'
. If you expect other characters (like uppercase or symbols), consider using a HashMap<Character, TrieNode>
instead.

Inserting Words into the Trie
Insertion involves going through each character of the word and adding nodes as needed. Start at the root node and for each character:
- If the child node doesn't exist, create it.
- Move to the child node.
- At the end of the word, mark the last node as the end of a word.
Here's how that looks in code:

public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (char ch : word.toCharArray()) { if (current.getChild(ch) == null) { current.setChild(ch, new TrieNode()); } current = current.getChild(ch); } current.setEndOfWord(true); } }
This ensures that all words are stored efficiently and overlapping prefixes are shared among different words.
Searching for Words or Prefixes
Searching works similarly to insertion but stops early if a character isn't found. There are two main cases:
- Exact word match – requires reaching the end of the word and checking if
isEndOfWord
is true. - Prefix search – just checks whether the path exists, regardless of
isEndOfWord
.
public boolean search(String word) { TrieNode current = root; for (char ch : word.toCharArray()) { current = current.getChild(ch); if (current == null) { return false; } } return current.isEndOfWord(); // Only return true if it's marked as end of a word } public boolean startsWith(String prefix) { TrieNode current = root; for (char ch : prefix.toCharArray()) { current = current.getChild(ch); if (current == null) { return false; } } return true; }
These methods make it easy to support both exact searches and autocomplete-style suggestions.
Handling Edge Cases and Improvements
A few edge cases are worth considering:
- Empty strings: You might want to decide whether to allow them or not.
- Case sensitivity: Convert input to lowercase before processing unless you want case-sensitive behavior.
- Memory optimization: For large datasets, consider compressing the trie or switching to a ternary search tree.
Also, if you're planning to implement deletion later, keep track of how many words use each node so you know when it's safe to remove one.
So, implementing a basic trie in Java boils down to creating a proper node structure and carefully handling insertion and lookup logic. It's not too complicated once you get the structure right, but small mistakes — like forgetting to mark the end of a word — can cause bugs that are tricky to trace.
Basically that's it.
The above is the detailed content of How to implement a Trie data structure in Java?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

The core of mastering Advanced SpringDataJPA is to select the appropriate data access method based on the scenario and ensure performance and maintainability. 1. In custom query, @Query supports JPQL and native SQL, which is suitable for complex association and aggregation operations. It is recommended to use DTO or interface projection to perform type-safe mapping to avoid maintenance problems caused by using Object[]. 2. The paging operation needs to be implemented in combination with Pageable, but beware of N 1 query problems. You can preload the associated data through JOINFETCH or use projection to reduce entity loading, thereby improving performance. 3. For multi-condition dynamic queries, JpaSpecifica should be used
