Repository navigation
Expand file tree
/
Copy pathTrie.java
More file actions
91 lines (84 loc) · 2.55 KB
/
Copy pathTrie.java
File metadata and controls
91 lines (84 loc) · 2.55 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.ArrayList;
import java.util.List;
public class Trie {
TrieNode root = new TrieNode();
/**
* Traverse through the trie to add a new Stop
* @param word array of Characters that act as the key to this Stop
* @param s Stop to add to trie
*/
public void add(char[] word, Stop s) {
TrieNode n = root;
for (Character c : word) {
if (!n.getChildChars().contains(c)) {
n.addChild(c);
}
n = n.getChild(c);
}
n.addStop(s);
}
/**
* Traverse through the trie to get a Stop given its key
* @param word key used to find stop
* @return Stop corresponding to key (null if not found)
*/
public List<Stop> get(char[] word) {
TrieNode n = root;
for (Character c : word) {
if (!n.getChildChars().contains(c)) {
return null;
}
n = n.getChild(c);
}
return n.getStops();
}
/**
* Get all Stops belonging to this node and its children
* @param word prefix used to find all stops
* @return List of Stops containing all stops belonging to node and children
*/
public List<Stop> getAll(char[] word) {
List<Stop> stops = new ArrayList<>();
TrieNode n = root;
for (Character c : word) {
if (!n.getChildChars().contains(c)) {
return stops; // return an empty list
}
n = n.getChild(c);
}
getAllFrom(n, stops);
return stops;
}
/**
* Helper method that collects all the stops from a node,
* recursively calls itself to collect all the stops from each child
* @param n Root node
* @param stops List of Stops currently collected
* @return List of Stops containing all stops belonging to current node and children
*/
public List<Stop> getAllFrom(TrieNode n, List<Stop> stops) {
stops.addAll(n.getStops());
for (TrieNode child : n) {
getAllFrom(child, stops);
}
return stops;
}
/**
* Get all the keys belonging to this node
* @return formatted String of all Character keys in node
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Character c : root.getChildChars()) {
sb.append(c).append(", ");
}
return sb.toString();
}
/**
* Make all the nodes 'disappear' by making a new root node
*/
public void clear() {
root = new TrieNode();
}
}