prefix tree

A trie, also called digital tree, radix tree or prefix tree, is a kind of search tree—an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Keys tend to be associated with leaves, though some inner nodes may correspond to keys of interest. Hence, keys are not necessarily associated with every node.

m2IvdA.png

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class  {
private boolean word;
private TrieNode[] children = new TrieNode[26];
}

public class Trie {
private TrieNode root;

public Trie() {
this.root = new TrieNode();
}

public void insert(String word) {
TrieNode node = root;

for (int i = 0; i < word.length(); i++) {
int idx = word.charAt(i) - 'a';

if (node.children[idx] == null)
node.children[idx] = new TrieNode();

node = node.children[idx];
}

node.word = true;
}

public boolean search(String word) {
TrieNode node = find(word);
return node != null && node.word;
}

public boolean startsWith(String prefix) {
TrieNode node = find(prefix);
return node != null;
}

private TrieNode find(String prefix) {
TrieNode node = root;

for (int i = 0; i < prefix.length(); i++) {
int idx = prefix.charAt(i) - 'a';

if (node.children[idx] == null)
return null;

node = node.children[idx];
}

return node;
}
}