/**
 * Generic class that implements a binaru search tree, building upon the 
 * existing BinaryTree class.
 *   @param <E> 
 * 
 *   @author Dave Reed 
 *   @version 10/15/13
 */
public class BinarySearchTree<E extends Comparable<? super E>> extends BinaryTree<E> {

    /**
     * Constructs an empty binary search tree.  NOTE: this constructor is not
     * necessary, since super() would be called automatically.
     */
    public BinarySearchTree() {
        super();
    }

    /**
     * Overrides the super.add method to add according to the BST property.
     *   @param value the value to be added to the tree
     */
    public void add(E value) {
        this.root = this.add(this.root, value);
    }
    private TreeNode<E> add(TreeNode<E> current, E value) {
        if (current == null) {
            return new TreeNode<E>(value, null, null);
        }

        if (value.compareTo(current.getData()) <= 0) {
            current.setLeft(this.add(current.getLeft(), value));
        }
        else {
            current.setRight(this.add(current.getRight(), value));
        }
        return current;
    }

    /**
     * Overrides the super.contains method to take advantage of binary search.
     *   @param value the value to be searched for
     *   @return true if that value is in the tree, otherwise false
     */
    public boolean contains(E value) {
        return this.contains(this.root, value);
    }
    private boolean contains(TreeNode<E> current, E value) {
        if (current == null) {
            return false;
        }
        else if (value.equals(current.getData())) {
            return true;
        }
        else if (value.compareTo(current.getData()) < 0) {
            return this.contains(current.getLeft(), value);
        }
        else {
            return this.contains(current.getRight(), value);
        }
    }


    public static void main(String[] args) {
        BinarySearchTree<Integer> tree = new BinarySearchTree<Integer>();
        tree.add(7);
        tree.add(2);
        tree.add(12);
        tree.add(1);
        tree.add(5);
        tree.add(6);
        tree.add(99);
        tree.add(88);

        System.out.println(tree);
        System.out.println("size = " + tree.size());
        System.out.println(tree.contains(2) + " " + tree.contains(5)
                                            + " " + tree.contains(8));

        tree.remove(2);
        System.out.println(tree);
        System.out.println("size = " + tree.size());
        System.out.println(tree.contains(2) + " " + tree.contains(5)
                                            + " " + tree.contains(8));
    }
}
