\0
/ \
a b-a-t-s
/|\
m s t
which contains [am, as, at, bat, bats]
The goal I'm trying to reach is to iterate through the trie to find if there's a next word or not, then if so get that word.
I would like to know your opinion on my approach.
The goal for this is that, at any point in the trie if there is a node that hasn't been visited, there's another word.
public boolean hasNext() {
if (position < this.trie.nodeCount()) return true;
return false;
}
What I'm trying to go for here is to check to see if the trie is not empty, then at the first trienode in the trie traverse it's children and descendants to find the next word in the trie. so for the trie above it would would go to a then first to m then back to a to s, then t. then eventually go onto b and it's children. then on the way, if it passes a full word, it will repeat that. so in this case, since bat is part of bats it would return 'bat' first then on the next iteration return bats
The logic in plain words is
string temp = null
if has next
while current != null
look at current nodes children
keep track of nodes visited
(temp += char at that node)
current = current nodes next node in trie (so a step down the trie)
if fullword at that node found return next
return false;
I also thought of trying a pre-order traversal but couldn't figure out how to do it with the arrays.
Current implementation:
public String next() {
String next = null;
if(hasNext()){
current = trie.root.children[position];
while(!current.children[position].isEndOfWord()){
position++;
current = current.children[position];
next += current.letter;
if (current.isEndOfWord()) return next;
}
}
return null;
}
Here's the declaration of the trienodes:
protected char letter = ' ';
protected TrieNode parentNode = null;
protected boolean fullWord = false;
protected TrieNode[] children = new TrieNode[26];
protected int prefixes = 0;
public TrieNode(char letter, TrieNode parentNode){
this.letter = letter;
this.parentNode = parentNode;
}
How the trie is built:
public void addWord(String s) {
if (hasWord(s)) return;
int index = 0;
TrieNode current = root;
char[] letters = s.toCharArray();
while(index < s.length()){
TrieNode child = current.children[letters[index] - 97];
if(child == null){
child = new TrieNode(letters[index], current);
child.prefixes++;
numOfNodes++;
}
current = child;
index++;
if(index == s.length()){
current.fullWord = true;
numOfWords++;
}
}
}