public class PrefixTree { private PTNode root; private int size; //constructor public PrefixTree ( ) { root = new PTNode (""); } public PTNode getRoot ( ) { return root; } public void setRoot (PTNode node) { root = node; } public int getSize ( ) { return size; } public boolean contains (String w) { // returns true if calling tree contains a node for the string w // this means that the path of w's letters leads to a node, // rather than anything to do with the "elem" fields of the nodes // assumes that w is a string of lower-case letters, else returns false PTNode current = root; for (int i = 0; i < w.length( ); i++) { if ((w.charAt(i) < 'a') || (w.charAt(i) > 'z')) return false; if (current.getChild (w.charAt(i)) == null) return false; current = current.getChild (w.charAt(i));} return true; } public void addString (String w) { // add new nodes to calling tree, for w and any of its prefixes that are new PTNode current = root; for (int i = 0; i < w.length( ); i++) { //if not a letter, break because of illegal input if ((w.charAt(i) < 'a') || (w.charAt(i) > 'z')) break; //otherwise, check if there is already a node with the next letter if (current.getChild (w.charAt(i)) == null){ //if not, add a new node current.setChild(w.charAt(i), w.substring(0, i+1)); //remember to increment size if(w.substring(i).length() == 1) size++; } // else a child node already exists, so just traverse down current = current.getChild(w.charAt(i)); } } }