Ternary Search Trees
root node (if any), the word for which to search, and the position of the first character. Finally, true is returned only if a node marking the end of a word was found; otherwise, false is returned to indicate the word was not found:
public boolean contains(CharSequence word) { assert word != null : “word can’t be null”;
assert word.length() > 0 : “word can’t be empty”;
Node node = search(_root, word, 0); return node != null && node.isEndOfWord();
}
The private search() method takes a node from which to start looking, the word to search for, and the position within the word from which to start. In return, search() provides the node containing the last character in the word, or null if the word was not found.
If there is no current node (node == null), the search can terminate immediately. Otherwise, the character at the current position is retrieved and the search begins.
If the current search character matches the one at the current node and there are more characters in the string (index + 1 < word.length()), the search progresses to the next letter, starting at the child node.
If the characters don’t match, the search character must exist either before or after the current node. If the character you are looking for sorts before the current node, then the search continues starting with the smaller sibling; otherwise, it must sort after the current node — in which case, the search continues with the larger sibling.
Eventually, either the letters in the search word run out or you run out of nodes. At this point, whichever node you are currently at (if any) is returned as the result:
private Node search(Node node, CharSequence word, int index) { assert word != null : “word can’t be null”;
if (node == null) { return null;
}
char c = word.charAt(index);
if (c == node.getChar()) {
if (index + 1 < word.length()) {
node = search(node.getChild(), word, index + 1);
}
} else if (c < node.getChar()) {
node = search(node.getSmaller(), word, index); } else {
node = search(node.getLarger(), word, index);
}
return node;
}
The methods add() and insert() work together to add new words to the tree.