forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TernarySearchTree.java
442 lines (376 loc) · 13.2 KB
/
TernarySearchTree.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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package com.jwetherell.algorithms.data_structures;
import com.jwetherell.algorithms.data_structures.interfaces.ITree;
/**
* In computer science, a ternary search tree is a type of trie (sometimes called a prefix tree) where nodes are arranged in a manner similar to a binary search tree, but with up to three
* children rather than the binary tree's limit of two.
* <br>
* <a href="https://www.cs.upc.edu/~ps/downloads/tst/tst.html">This implementation is based on Jon Bentley and Bob Sedgewick's paper.</a>
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Ternary_search_tree">Ternary Search Tree (Wikipedia)</a>
* <br>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public class TernarySearchTree<C extends CharSequence> implements ITree<C> {
protected INodeCreator creator;
protected Node root;
private int size = 0;
public TernarySearchTree() {
this.creator = new INodeCreator() {
/**
* {@inheritDoc}
*/
@Override
public Node createNewNode(Node parent, Character character, boolean isWord) {
return (new Node(parent, character, isWord));
}
};
}
/**
* Constructor with external Node creator.
*/
public TernarySearchTree(INodeCreator creator) {
this.creator = creator;
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(C value) {
if (value == null)
return false;
final int before = size;
if (root == null)
this.root = insert(null, null, value, 0);
else
insert(null, root, value, 0);
final int after = size;
// Successful if the size has increased by one
return (before==(after-1));
}
private Node insert(Node parent, Node node, C value, int idx) {
if (idx >= value.length())
return null;
final char c = value.charAt(idx);
final boolean isWord = (idx==(value.length()-1));
if (node == null) {
// Create new node
node = this.creator.createNewNode(parent, c, isWord);
// If new node represents a "word", increase the size
if (isWord)
size++;
} else if (c==node.character && isWord && !node.isWord) {
// Changing an existing node into a "word" node
node.isWord = true;
// Increase the size
size++;
}
if (c < node.character) {
node.loKid = insert(node, node.loKid, value, idx);
} else if (c > node.character) {
node.hiKid = insert(node, node.hiKid, value, idx);
} else if (idx < (value.length()-1)) {
// Not done with whole string yet
node.kid = insert(node, node.kid, value, ++idx);
}
return node;
}
/**
* {@inheritDoc}
*/
@Override
public C remove(C value) {
if (value == null || root == null)
return null;
// Find the node
final Node node = search(root, value, 0);
// If node was not found or the node is not a "word"
if (node == null || !node.isWord)
return null;
// Node was found, remove from tree if possible
node.isWord = false;
remove(node);
size--;
return value;
}
private void remove(Node node) {
// If node is a "word", stop the recursive pruning
if (node.isWord)
return;
// If node has at least one child, we cannot prune it.
if (node.loKid!=null || node.kid!=null || node.hiKid!=null)
return;
// Node has no children, prune the node
final Node parent = node.parent;
if (parent != null) {
// Remove node from parent
if (parent.loKid==node) {
parent.loKid = null;
} else if (parent.hiKid==node) {
parent.hiKid = null;
} else if (parent.kid==node) {
parent.kid = null;
}
// If parent is not a "word" node, go up the tree and prune if possible
if (!node.isWord)
remove(parent);
} else {
// If node doesn't have a parent, it's root.
this.root = null;
}
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
root = null;
size = 0;
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(C value) {
if (value == null)
return false;
// Find the node
final Node node = search(root, value, 0);
// If node isn't null and it represents a "word" then the tree contains the value
return (node!=null && node.isWord);
}
private Node search(Node node, C value, int idx) {
if (node == null || idx>=value.length())
return null;
final char c = value.charAt(idx);
if (c < node.character)
return search(node.loKid, value, idx);
if (c > node.character)
return search(node.hiKid, value, idx);
if (idx < (value.length()-1)) {
// c == node.char and there is still some characters left in the search string
return search(node.kid, value, ++idx);
}
return node;
}
@Override
public int size() {
return size;
}
@Override
public boolean validate() {
if (this.root == null)
return true;
return validate(root);
}
private boolean validate(Node node) {
boolean result = false;
if (node.loKid != null) {
if (node.loKid.character >= node.character)
return false;
result = validate(node.loKid);
if (!result)
return false;
}
if (node.kid != null) {
result = validate(node.kid);
if (!result)
return false;
}
if (node.hiKid != null) {
if (node.hiKid.character <= node.character)
return false;
result = validate(node.hiKid);
if (!result)
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
public java.util.Collection<C> toCollection() {
return (new JavaCompatibleTree<C>(this));
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return TreePrinter.getString(this);
}
protected static interface INodeCreator {
/**
* Create a new node for sequence.
*
* @param parent
* node of the new node.
* @param character
* which represents this node.
* @param isWord
* signifies if the node represents a word.
* @return Node which was created.
*/
public Node createNewNode(Node parent, Character character, boolean isWord);
}
protected static class TreePrinter {
public static <C extends CharSequence> void print(TernarySearchTree<C> tree) {
System.out.println(getString(tree));
}
public static <C extends CharSequence> String getString(TernarySearchTree<C> tree) {
if (tree.root == null)
return "Tree has no nodes.";
return getString(tree.root, "", null, true);
}
protected static String getString(Node node, String prefix, String previousString, boolean isTail) {
final StringBuilder builder = new StringBuilder();
String string = "";
if (previousString != null)
string = previousString;
builder.append(prefix + (isTail ? "└── " : "├── ") + ((node.isWord == true) ?
("(" + node.character + ") " + string+String.valueOf(node.character))
:
node.character) + "\n"
);
if (node.loKid != null)
builder.append(getString(node.loKid, prefix + (isTail ? " " : "│ "), string, false));
if (node.kid != null)
builder.append(getString(node.kid, prefix + (isTail ? " " : "│ "), string+String.valueOf(node.character), false));
if (node.hiKid != null)
builder.append(getString(node.hiKid, prefix + (isTail ? " " : "│ "), string, true));
return builder.toString();
}
}
protected static class Node {
private final Node parent;
private final char character;
private boolean isWord;
protected Node loKid;
protected Node kid;
protected Node hiKid;
protected Node(Node parent, char character, boolean isWord) {
this.parent = parent;
this.character = character;
this.isWord = isWord;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("char=").append(this.character).append('\n');
if (this.loKid != null)
builder.append('\t').append("lo=").append(this.loKid.character).append('\n');
if (this.kid != null)
builder.append('\t').append("eq=").append(this.kid.character).append('\n');
if (this.hiKid != null)
builder.append('\t').append("hi=").append(this.hiKid.character).append('\n');
return builder.toString();
}
}
@SuppressWarnings("unchecked")
public static class JavaCompatibleTree<C extends CharSequence> extends java.util.AbstractCollection<C> {
private TernarySearchTree<C> tree = null;
public JavaCompatibleTree(TernarySearchTree<C> tree) {
this.tree = tree;
}
/**
* {@inheritDoc}
*/
@Override
public boolean add(C value) {
return tree.add(value);
}
/**
* {@inheritDoc}
*/
@Override
public boolean remove(Object value) {
return (tree.remove((C)value)!=null);
}
/**
* {@inheritDoc}
*/
@Override
public boolean contains(Object value) {
return tree.contains((C)value);
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return tree.size;
}
/**
* {@inheritDoc}
*
* WARNING: This iterator makes a copy of the tree's contents during it's construction!
*/
@Override
public java.util.Iterator<C> iterator() {
return (new TreeIterator<C>(tree));
}
private static class TreeIterator<C extends CharSequence> implements java.util.Iterator<C> {
private TernarySearchTree<C> tree = null;
private TernarySearchTree.Node lastNode = null;
private java.util.Iterator<java.util.Map.Entry<Node, String>> iterator = null;
protected TreeIterator(TernarySearchTree<C> tree) {
this.tree = tree;
java.util.Map<TernarySearchTree.Node,String> map = new java.util.LinkedHashMap<TernarySearchTree.Node,String>();
if (this.tree.root!=null) {
getNodesWhichRepresentsWords(this.tree.root,"",map);
}
iterator = map.entrySet().iterator();
}
private void getNodesWhichRepresentsWords(TernarySearchTree.Node node, String string, java.util.Map<TernarySearchTree.Node,String> nodesMap) {
final StringBuilder builder = new StringBuilder(string);
if (node.isWord)
nodesMap.put(node,builder.toString());
if (node.loKid != null) {
Node child = node.loKid;
getNodesWhichRepresentsWords(child, builder.toString(), nodesMap);
}
if (node.kid != null) {
Node child = node.kid;
getNodesWhichRepresentsWords(child, builder.append(node.character).toString(), nodesMap);
}
if (node.hiKid != null) {
Node child = node.hiKid;
getNodesWhichRepresentsWords(child, builder.toString(), nodesMap);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
if (iterator!=null && iterator.hasNext())
return true;
return false;
}
/**
* {@inheritDoc}
*/
@Override
public C next() {
if (iterator==null)
return null;
java.util.Map.Entry<TernarySearchTree.Node,String> entry = iterator.next();
lastNode = entry.getKey();
return (C)entry.getValue();
}
/**
* {@inheritDoc}
*/
@Override
public void remove() {
if (iterator==null || tree==null)
return;
iterator.remove();
this.tree.remove(lastNode);
}
}
}
}