Node structure
class TrieNode {
Map children = new HashMap<>();
boolean isEnd;
} Advertisement
Insert + search
void insert(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
cur = cur.children.computeIfAbsent(c, k -> new TrieNode());
}
cur.isEnd = true;
}
boolean search(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
cur = cur.children.get(c);
if (cur == null) return false;
}
return cur.isEnd;
}Advertisement
Array vs HashMap children
Array (size 26 for lowercase): fast + memory hungry. HashMap: flexible + slower per lookup. Choose per alphabet size.
Compressed trie (Radix)
Merge single-child paths. Less memory. More complex code. Great for sparse tries.