public class BinarySearchTree> { SparseVector t; public BinarySearchTree() { t = new SparseVector(); } private int leftChild(int parent) { return 2 * parent + 1; } private int rightChild(int parent) { return 2 * parent + 2; } private T valueAt(int pos) { return t.get(pos); } private void addHelper(T value, int node) { int child = value.compareTo(valueAt(node)) < 0 ? leftChild(node) : rightChild(node); if (valueAt(child) != null) { // is there a child subtree? // if yes, recurse addHelper(value, child); } else { // base case: insert at child pos t.add(child, value); } } public void add(T value) { // we now need a special case for the // first insertion because a new BinarySearchTree // will be empty. if (valueAt(0) == null) { t.add(0, value); return; } addHelper(value, 0); // start at the root } private String toStringHelper(int root) { T left = valueAt(leftChild(root)); T right = valueAt(rightChild(root)); if (left == null && right == null) { return valueAt(root).toString(); } else if (left == null) { return valueAt(root) + " " + toStringHelper(rightChild(root)); } else if (right == null) { return toStringHelper(leftChild(root)) + " " + valueAt(root); } else { return toStringHelper(leftChild(root)) + " " + valueAt(root) + " " + toStringHelper(rightChild(root)); } } @Override public String toString() { if (valueAt(0) == null) { return ""; } else { return toStringHelper(0); } } }