/**
 * A binary search tree on Strings.
 *
 */
public class BST {
    
    TreeNode root;     // The root of the BST
    
    /**
     * Constructor.
     */
    public BST () {
        root = null;
    }
    
    /**
     * Insert.
     * Nothing happens if the string is already in the BST.
     */
    public void insert (String string) {
        root = insert(string, root);
    }
    
    private static TreeNode insert (String string, TreeNode node) {
        if (node == null) return new TreeNode(string);
        int compare = string.compareTo(node.datum);
        if (compare < 0) node.lchild = insert(string, node.lchild);
        else if (compare > 0) node.rchild = insert(string, node.rchild);
        return node;
    }
    
    /**
     * Show the contents of the BST in alphabetical order.
     */
    public void show () {
        show(root); System.out.println();
    }
    
    private static void show (TreeNode node) {
        if (node == null) return;
        show(node.lchild);
        System.out.print(node.datum + " ");
        show(node.rchild);
    }
    
    /**
     * toString.
     * Prints a "sideways" version of the tree.  
     * The root is on the left; left and right children correspond to down 
     * and up, respectively.
     */
    public String toString () {
        return toString("", root);
    }
    
    private static String toString (String prefix, TreeNode node) {
        if (node == null) return "";
        String string = prefix + node.datum.toString();
        if (node.rchild != null) 
            string = toString("    " + prefix, node.rchild) + "\n" + string;
        if (node.lchild != null)
            string = string + "\n" + toString("    " + prefix, node.lchild);
        return string;
    }
}

/**
 * TreeNode (a helper class; visible to other classes in same package).
 */
class TreeNode {
    
    String datum;                // Data for a node
    TreeNode lchild, rchild;     // Left and right children.
    
    /**
     * Constructor.
     */
    public TreeNode (String datum) {
        this.datum = datum;
        lchild = null; rchild = null;
    }
}

