import java.util.*; // An IntSearchTree object represents an entire binary search tree of ints. // Class invariant: // - nodes to the left of a root have smaller values // - nodes to the right of a root have larger values // - there are no duplicates public class IntSearchTree { private IntTreeNode overallRoot; private int size; // Constructs an empty binary tree public IntSearchTree() { overallRoot = null; size = 0; } // returns true if the value is found in this tree, false otherwise public boolean contains(int value) { return contains(overallRoot, value); } private boolean contains(IntTreeNode root, int value) { if (root == null) { return false; } else if (root.data == value) { return true; } else if (value < root.data) { return contains(root.left, value); } else { return contains(root.right, value); } } // adds a value to the bst // post: the tree is still a valid bst public void add(int value) { overallRoot = add(overallRoot, value); } private IntTreeNode add(IntTreeNode root, int value) { if (root == null) { size++; root = new IntTreeNode(value); // return root; // useful for visualizing with jGRASP debugger } else if (value < root.data) { root.left = add(root.left, value); } else if (value > root.data) { root.right = add(root.right, value); } return root; } // Returns the minimum value from this BST. // Throws a NoSuchElementException if the tree is empty. public int getMin() { if (overallRoot == null) { throw new NoSuchElementException(); } return getMin(overallRoot); } private int getMin(IntTreeNode root) { if (root.left == null) { return root.data; } else { return getMin(root.left); } } // Removes the node with the given value from this BST. public void remove(int value) { overallRoot = remove(overallRoot, value); } private IntTreeNode remove(IntTreeNode root, int value) { if (root != null) { if (value < root.data) { root.left = remove(root.left, value); } else if (value > root.data) { root.right = remove(root.right, value); } else { // found it! size--; if (root.left == null && root.right == null) { // leaf node root = null; } else if (root.right == null) { root = root.left; } else if (root.left == null) { root = root.right; } else { int min = getMin(root.right); root.data = min; size++; // to compensate for the remove below root.right = remove(root.right, min); } } } return root; } public int size() { return size; } public boolean isEmpty() { return size == 0; } }