package class7_2_BinarySearchTree_021; import edu.msoe.se1010.winPlotter.WinPlotter; import java.util.Set; /** * 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; //---- START of height method (and helpers) ---- /** * The height method returns the height of the tree or the longest possible branch the tree can take * @return an integer representing the height of the tree */ public int height(){ return height(root); } /** * Helper method for the height method. Used recursively to find the height of the tree * @param subroot * @return */ private int height(Node subroot){ if(subroot == null){ return 0; } else { int leftHeight = height(subroot.left); int rightHeight = height(subroot.right); if(leftHeight >= rightHeight) return leftHeight+1; else return rightHeight+1; } } //---------- END OF height method -------- 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