-
Notifications
You must be signed in to change notification settings - Fork 522
/
Trie.java
40 lines (36 loc) · 1.06 KB
/
Trie.java
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
package strings;
// https://en.wikipedia.org/wiki/Trie
public class Trie {
static class TrieNode {
TrieNode[] children = new TrieNode[128];
boolean leaf;
}
public static void insertString(TrieNode root, String s) {
TrieNode cur = root;
for (char ch : s.toCharArray()) {
if (cur.children[ch] == null) {
cur.children[ch] = new TrieNode();
}
cur = cur.children[ch];
}
cur.leaf = true;
}
public static void printSorted(TrieNode node, String s) {
for (char ch = 0; ch < node.children.length; ch++) {
TrieNode child = node.children[ch];
if (child != null)
printSorted(child, s + ch);
}
if (node.leaf) {
System.out.println(s);
}
}
// Usage example
public static void main(String[] args) {
TrieNode root = new TrieNode();
insertString(root, "hello");
insertString(root, "world");
insertString(root, "hi");
printSorted(root, "");
}
}