package class7_1_BinarySearchTree_021; import edu.msoe.se1010.winPlotter.WinPlotter; /** * This class is a super-cool combination * of a SortedArrayList and a LinkedList. * * Like the SortedArrayList, the elements are always sorted. * Like the LinkedList, once we find where something should be, * we can insert it in O(1) time just by editing a few links. * * @param the type of the contained obects */ public class BinarySearchTree> { private Node root; public void add(E element) { if(root == null) { root = new Node(null,null,element); } else { add(root, element); } } private void add(Node subRoot, E element) { if(subRoot.value.compareTo(element) < 0) { if(subRoot.left == null) { subRoot.left = new Node(null, null, element); } else { add(subRoot.left, element); } } else if(subRoot.value.compareTo(element) > 0) { if(subRoot.right == null) { subRoot.right = new Node(null,null,element); } else { add(subRoot.right, element); } } else { // the two are equal System.err.println("Warning: attempt to add an existing node"); System.err.println("Overwriting previous value"); subRoot.value = element; } } private class Node { private Node left; private Node right; private E value; private Node(Node left, Node right, E value) { this.left = left; this.right = right; this.value = value; } } public boolean isEmpty() { return root == null; } public int size() { return size(root); } private int size(Node subTreeRoot) { if(subTreeRoot == null) { return 0; } else { return 1+size(subTreeRoot.left) +size(subTreeRoot.right); } } public void print() { printTree(root, 0); } private void printTree(Node current, int depth) { if(current != null) { printTree(current.left,depth+1); for(int i=0;i