import structure5.*; public class ImplicitBinarySearchTree,V> { SparseVector> t; public ImplicitBinarySearchTree() { t = new SparseVector>(); } private int leftChild(int parent) { return 2 * parent + 1; } private int rightChild(int parent) { return 2 * parent + 2; } private ComparableAssociation nodeAt(int pos) { return t.get(pos); } private void addHelper(int pos, ComparableAssociation a) { int childpos = a.compareTo(nodeAt(pos)) < 0 ? leftChild(pos) : rightChild(pos); if (nodeAt(childpos) != null) { // is there a child subtree? // if yes, recurse addHelper(childpos, a); } else { // base case: insert at child pos t.add(childpos, a); } } public void add(K key, V value) { ComparableAssociation a = new ComparableAssociation<>(key, value); // we now need a special case for the // first insertion because a new BinarySearchTree // will be empty. if (nodeAt(0) == null) { t.add(0, a); return; } addHelper(0, a); // start at the root } private String toStringHelper(int root) { ComparableAssociation left = nodeAt(leftChild(root)); ComparableAssociation right = nodeAt(rightChild(root)); if (left == null && right == null) { return nodeAt(root).toString(); } else if (left == null) { return nodeAt(root) + " " + toStringHelper(rightChild(root)); } else if (right == null) { return toStringHelper(leftChild(root)) + " " + nodeAt(root); } else { return toStringHelper(leftChild(root)) + " " + nodeAt(root) + " " + toStringHelper(rightChild(root)); } } /** * Returns key and value if it is in the tree using * binary search. Returns null if the key is not in * the tree. */ public ComparableAssociation get(K key) { if (nodeAt(0) == null) { return null; } ComparableAssociation a = new ComparableAssociation<>(key, null); return getHelper(0, a); } public ComparableAssociation getHelper(int pos, ComparableAssociation a) { ComparableAssociation node = nodeAt(pos); // was the last position a leaf? // if so, stop and return null if (node == null) { return null; } // otherwise, do comparisons int cmp = a.compareTo(node); if (cmp == 0) { // this is the node we were looking for return node; } else if (cmp < 0) { // key is somewhere on the left return getHelper(leftChild(pos), a); } else { // key is somewhere on the right return getHelper(rightChild(pos), a); } } @Override public String toString() { if (nodeAt(0) == null) { return ""; } else { return toStringHelper(0); } } }