I have written the following Java code for inserting and searching for a word in Java:
public class trie {
private class TrieNode{
TrieNode[] children;
boolean isWord;
public TrieNode() {
this.children = new TrieNode[26];
this.isWord = false;
for(int i= 0; i < 26; i++) {
this.children[i] = null;
}
}
}
TrieNode root;
public trie() {
root = new TrieNode();
}
public void insert(String s) {
if(s == null || s.isEmpty()) {
throw new IllegalArgumentException("Invalid Input");
}
s = s.toLowerCase();
TrieNode current = root;
for(int i=0; i < s.length(); i++) {
char c = s.charAt(i);
int index = c - 'a';
if(current.children[index]==null) {
TrieNode node = new TrieNode();
current.children[i] = node;
current = node;
} else {
current = current.children[index];
}
}
current.isWord = true;
}
public boolean search(String s) {
if(s==null || s.isEmpty()) {
throw new IllegalArgumentException("Invalid or empty string");
}
s=s.toLowerCase();
TrieNode current = root;
for(int i=0; i < s.length(); i++) {
int index = s.charAt(i) - 'a';
if(current.children[index] == null) {
return false;
} else {
current = current.children[index];
}
}
return current.isWord;
}
public static void main(String []args) {
trie t = new trie();
t.insert("car");
t.insert("cat");
t.insert("care");
System.out.println("Insert successful!!");
System.out.println(t.search("car"));
}
}
The search function returns false as output currently:
Insert successful!! false
I can't figure out where I am going wrong though. I checked various resources available online too. Any pointers?
Problem is that you assign the node
to the wrong child of the current node
within the insert()
function.
Change this line of code:
current.children[i] = node;
to this:
current.children[index] = node;
Problem will be solved.