public class TernarySearchTrie {
private static class TSTNode{
private String value=null;
private TSTNode left;
private TSTNode mid;
private TSTNode right;
private char splitChar;
private TSTNode()
{}
private TSTNode(char c){
splitChar=c;
}
}
private TSTNode root=new TSTNode();
public void addWord(String word)
{
TSTNode nodeRoot=root;
for (int i = 0; i < word.length(); i++)
{
nodeRoot=getOrCreate(word.charAt(i),nodeRoot);
}
nodeRoot.value=word;
}
private TSTNode getOrCreate(char key,TSTNode node)
{
if(node.mid==null)
{
node.mid=new TSTNode(key);
return node.mid;
}
TSTNode current=node.mid;
while(true)
{
int dis=key-current.splitChar;
if(dis==0)
{
return current;
}
else if(dis<0)
{
if(current.left==null)
{
current.left=new TSTNode(key);
return current.left;
}
current=current.left;
}
else
{
if(current.right==null)
{
current.right=new TSTNode(key);
return current.right;
}
current=current.right;
}
}
}
public String getNode(String word)
{
TSTNode nodeRoot=root;
for (int i = 0; i < word.length(); i++)
{
nodeRoot=getNode(word.charAt(i),nodeRoot);
if(nodeRoot==null)
{
return null;
}
}
return nodeRoot.value;
}
private TSTNode getNode(char key,TSTNode node)
{
if(node.mid==null)
{
return null;
}
TSTNode current=node.mid;
while(true)
{
int dis=key-current.splitChar;
if(dis==0)
{
return current;
}
else if(dis<0)
{
if(current.left==null)
{
return null;
}
current=current.left;
}
else
{
if(current.right==null)
{
return null;
}
current=current.right;
}
}
}
}
TernarySearchTrie tree=new TernarySearchTrie();
tree.addWord("is");
tree.addWord("in");
tree.addWord("it");
tree.addWord("be");
tree.addWord("by");
tree.addWord("as");
tree.addWord("at");
tree.addWord("he");
tree.addWord("on");
tree.addWord("or");
tree.addWord("of");
tree.addWord("to");
System.out.println(tree.getNode("is"));
System.out.println(tree.getNode("on"));
System.out.println(tree.getNode("to"));