I have a method that finds all the possible words in a prefix tree. It takes in a node and finds all possible words for that node. However, I need it to be able to take in combinations of nodes and find the combined possible words. The method will search through the trie, which is filled with a dictionary of words. For example rather then finding all the possible words from one letter with the prefix 'a', it could find all the possible words from the prefix 'ab' or 'abo'. I just don't know how to search with a combination of nodes rather then from just one node.
public void findWords(Node node) {
if(node == null) return;
//searches through the branches of the node
// R is 26(the branches from each node on the trie)
// each one being a letter of the alphabet.
for(int i = 0; i < R; i++) {
if(node.next[i] != null) {
//printing each character
System.out.print((char) (97 + i));
//identifying letter combo
if(node.next[i].isWord == true) {
System.out.println();
}
//back into the loop
findWords(node.next[i]);
}
}
}
node class:
public class TextPredictTrie {
private final int R = 26; // the trie branches
private Node root = new Node(); // the root node
// the t9 mapped array which maps number to string on the typing board
private String[] t9 = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
// trie node definition
private class Node {
private boolean isWord;
private Node[] next;
public Node() {
this(false);
}
public Node(boolean isWord) {
this.isWord = isWord;
this.next = new Node[R];
}
}
I don't really understand your question, but what you're doing seems to be wrong in the first place, because once you output a newline, you lose the complete prefix of your search path. You should probably change the signature of findWords(Node node)
to findWords(String prefix, Node node)
, in order to maintain the prefix. I would furthermore suggest a slight restructuring of the method:
public void findWords(String prefix, Node node) {
if(node == null) return;
if(node.isWord) // Check here
System.out.println(prefix);
//searches through the branches of the node
// R is 26(the branches from each node on the trie)
// each one being a letter of the alphabet.
for(int i = 0; i < R; i++) {
if(node.next[i] != null) {
// append next character to prefix
findWords(prefix + ('a' + i), node.next[i]);
}
}
}
Needless to say, this is very inefficient. You might want to check out the StringBuilder
class, append(char)
before recursing and removeCharAt(length-1)
when returning from the recursive call.