import java.util.*; public class BinarySearchTree , V> implements Iterable { private class Node { K key; V data; Node left, right, parent; Node (K key, V data, Node parent) { this.key=key; this.data=data; this.parent=parent; } } Node root; // Inserts (key, data) into the tree rooted at current // returns the tree after insertion has been completed private Node insert(K key, V data, Node cur, Node parent) { if (cur == null) return new Node (key, data, parent); if (key.compareTo(cur.key)<0) cur.left = insert(key, data, cur.left, cur); else cur.right = insert(key, data, cur.right, cur); return cur; } public void insert (K key, V data) { root = insert (key, data, root, null); } private void remove (Node node) { // if there is only one child to save if (node.left == null || node.right == null) { Node child; // find the child to save if (node.left == null) child = node.right; else child = node.left; // attach it wherever the current node was attached if (node == root) { root = child; if (child != null) child.parent = null; } else { if (node.parent.left == node) node.parent.left = child; else node.parent.right = child; if (child != null) child.parent = node.parent; } } else { // there are two children to save Node toRemove; // find the inorder successor to remove toRemove = node.right; while (toRemove.left!=null) toRemove = toRemove.left; // copy key and data to current node, and remove the successor node.data = toRemove.data; node.key = toRemove.key; remove (toRemove); } } public Iterator iterator() { return new InOrderIterator(); } private class InOrderIterator implements Iterator { Node justReturned, next; private InOrderIterator() { // FILL IN HERE } public boolean hasNext() { // FILL IN HERE } public V next() { if (!hasNext()) throw new NoSuchElementException(); // FILL IN HERE } public void remove() { if (justReturned == null) // either next has not been called at all or not since last remove throw new IllegalStateException(); // BinarySearchTree.this refers to the tree in which our inner class InOrderIterator resides BinarySearchTree.this.remove (justReturned); // call the remove method of the parent class } } }