I'm attempting to write a class to create a prefix tree (or trie) with an addWord method that takes in a string as a parameter and stores each character in it's appropriate place in the tree.
However, I keep getting a NullPointerException in the line of my first if statement (indicated below). Can anyone help me understand what's causing this? Thank you in advance!
public class PrefixTree {
private Node root;
public PrefixTree () {
root = new Node();
}
public void addWord(String word) {
int length = word.length();
char currentCharacter = word.charAt(0);
Node currentNode = root;
//Essentially this is saying "for each character in the string..."
for(int i=0; i<length; i++){
currentCharacter= word.charAt(i);
//if the children array of parent node does not contain the current character
//create a new node and add it to the parent array.
//HERE IS WHERE THE EXCEPTION IS BEING THROWN
if(currentNode.children[currentCharacter - 'a'] == null) {
Node newNode = new Node();
//set the node character value equal to the current character
newNode.c=currentCharacter;
//add the new node to the child array of its parent node
currentNode.children[currentCharacter - 'a']= newNode;
//if this is the last character in the word, change the endWord value to true
if( i == length-1) {
newNode.endWord = true;
//stores the complete string in its ending node
newNode.fullWord = word;
}
//set current node equal to the new node created and repeat the process
currentNode = newNode;
}
}
}
private class Node {
public boolean endWord;
public char c;
public Node[] children;
public String fullWord;
public Node(){
c = '0';
endWord = false;
Node[] children = new Node[26];
//Stores the complete string of a word ending w/ this node to make life easier later
String fullWord = null;
}
}
public static void main(String [] args){
PrefixTree test = new PrefixTree();
test.addWord("test");
}
}
Because you're assigning to local variables in Node
's constructor. Change to this:
public Node(){
c = '0';
endWord = false;
this.children = new Node[26];
//Stores the complete string of a word ending w/ this node to make life easier later
this.fullWord = null;
}