forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTernarySearchTree.java
More file actions
81 lines (70 loc) · 2.23 KB
/
TernarySearchTree.java
File metadata and controls
81 lines (70 loc) · 2.23 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
package main.java.com.thealgorithms.datastructures.trees;
/**
* Ternary Search Tree (TST) implementation.
* Stores strings and supports insertion, search, and prefix checking.
*
* Time Complexity:
* - Insert: O(m), where m = word length
* - Search: O(m)
*/
public class TernarySearchTree {
private Node root;
private static class Node {
char character;
boolean isEndOfWord;
Node left, middle, right;
Node(char character) {
this.character = character;
}
}
/** Insert a word into the TST */
public void insert(String word) {
root = insert(root, word, 0);
}
private Node insert(Node node, String word, int index) {
char ch = word.charAt(index);
if (node == null) {
node = new Node(ch);
}
if (ch < node.character) {
node.left = insert(node.left, word, index);
} else if (ch > node.character) {
node.right = insert(node.right, word, index);
} else {
if (index + 1 < word.length()) {
node.middle = insert(node.middle, word, index + 1);
} else {
node.isEndOfWord = true;
}
}
return node;
}
/** Search if a word exists in TST */
public boolean search(String word) {
return search(root, word, 0);
}
private boolean search(Node node, String word, int index) {
if (node == null) return false;
char ch = word.charAt(index);
if (ch < node.character) {
return search(node.left, word, index);
} else if (ch > node.character) {
return search(node.right, word, index);
} else {
if (index + 1 == word.length()) {
return node.isEndOfWord;
}
return search(node.middle, word, index + 1);
}
}
// Example usage
public static void main(String[] args) {
TernarySearchTree tst = new TernarySearchTree();
tst.insert("cat");
tst.insert("cap");
tst.insert("bat");
System.out.println(tst.search("cat")); // true
System.out.println(tst.search("cap")); // true
System.out.println(tst.search("can")); // false
}
}