package class7_1_BinarySearchTree_051; import edu.msoe.se1010.winPlotter.WinPlotter; import java.util.Comparator; /** * 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> extends Object { private Node root; 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 current) { if(current == null) { return 0; } else { return 1 + size(current.left) + size(current.right); } } public void add(E e) { // E value = root.value; // if(value.compareTo(e) < 0) /*...*/; if(root == null) { root = new Node(null, null, e); } else { add(root, e); } } /** * * @param subRoot root of sub-tree (MUST NOT BE NULL) * @param e objce t to add */ private void add(Node subRoot, E e) { if(e.compareTo(subRoot.value) < 0) { if(subRoot.left == null) { subRoot.left = new Node(null, null, e); } else { add(subRoot.left, e); } } else if(e.compareTo(subRoot.value) > 0) { if(subRoot.right == null) { subRoot.right = new Node(null, null, e); } else { add(subRoot.right, e); } } else { System.err.println("Warning: Replacing existing node"); System.err.println("(Duplicate add)"); subRoot.value = e; } } public E find(E e) { return find(root,e); } private E find(Node subRoot, E e) { if(subRoot == null) { return null; } else if(e.compareTo(subRoot.value) == 0) { return subRoot.value; } if(e.compareTo(root.value) < 0) { return find(root.left,e); } else { return find(root.right,e); } } 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