-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.java
101 lines (87 loc) · 1.92 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
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
class TrieNode{
char data;
boolean isTerminating;
TrieNode children[];
int childCount;
public TrieNode(char data) {
this.data = data;
isTerminating = false;
children = new TrieNode[26];
childCount = 0;
}
}
public class Trie {
private TrieNode root;
private int numWords;
public Trie() {
root = new TrieNode('\0');
numWords = 0;
}
public void remove(String word){
if(remove(root, word)) {
numWords--;
}
}
private boolean remove(TrieNode root, String word) {
if(word.length() == 0){
if(root.isTerminating) {
root.isTerminating = false;
return true;
}
else {
return false;
}
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
return false;
}
boolean ans = remove(child, word.substring(1));
// We can remove child node only if it is non terminating and its number of children are 0
if(!child.isTerminating && child.childCount == 0){
root.children[childIndex] = null;
child = null;
root.childCount--;
}
return ans;
}
public boolean search(TrieNode root, String word){
if(word.length() == 0){
return root.isTerminating;
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
return false;
}
return search(child,word.substring(1));
}
private boolean add(TrieNode root, String word){
if(word.length() == 0){
if(root.isTerminating) {
return false;
}
else {
root.isTerminating = true;
return true;
}
}
int childIndex = word.charAt(0) - 'a';
TrieNode child = root.children[childIndex];
if(child == null){
child = new TrieNode(word.charAt(0));
root.children[childIndex] = child;
root.childCount++;
}
return add(child, word.substring(1));
}
public void add(String word){
if(add(root, word)) {
numWords++;
}
}
public int countWords() {
// Write your code here
}
}