import java.util.Iterator; class BinarySearchTree> implements Iterable { private T value; private BinarySearchTree left; private BinarySearchTree right; public BinarySearchTree(T value) { this.value = value; this.left = null; this.right = null; } public BinarySearchTree(T value, BinarySearchTree left, BinarySearchTree right) { this.value = value; this.left = left; this.right = right; } public void setLeft(BinarySearchTree left) { this.left = left; } public void setRight(BinarySearchTree right) { this.right = right; } public void setValue(T value) { this.value = value; } public T getValue() { return value; } public BinarySearchTree getLeft() { return left; } public BinarySearchTree getRight() { return right; } /** * Computes the (edge) height. * Note that this is an instance method, so * it must have an instance of BinarySearchTree, * which complicates the implementation. */ public int getHeight() { if (left == null && right == null) { return 0; } else if (left == null) { return 1 + right.getHeight(); } else if (right == null) { return 1 + left.getHeight(); } else { return 1 + Math.max(left.getHeight(), right.getHeight()); } } /** * Computes the (edge) height. * Note that this is a static method. Since * it can always check that root == null directly, * the implementation matches the simple recursive * height definition shown in class. */ public static > int getHeight(BinarySearchTree root) { if (root == null) { return -1; } else { return 1 + Math.max(getHeight(root.getLeft()), getHeight(root.getRight())); } } /** * Inserts a value into the appropriate location, * modifying the tree in-place. */ protected void add(T value) { if (value.compareTo(getValue()) < 0) { // goes on the left if (left != null) { // is there a left subtree? // if so, recurse left.add(value); } else { // base case: insert to the left setLeft(new BinarySearchTree(value)); } } else { // goes on the right if (right != null) { // is there a right subtree? // if so, recurse right.add(value); } else { // base case: insert to the right setRight(new BinarySearchTree(value)); } } } public Iterator iterator() { return new BinarySearchTreeIterator(this); } @Override public String toString() { if (getLeft() == null && getRight() == null) { return value.toString(); } else if (getLeft() == null) { return value.toString() + " " + getRight().toString(); } else if (getRight() == null) { return getLeft().toString() + " " + value.toString(); } else { return getLeft().toString() + " " + value.toString() + " " + getRight().toString(); } } }