// Textbook fragment 08.12 /** Returns the parent of v. */ public Position parent(Position v) throws InvalidPositionException, BoundaryViolationException { if (isRoot(v)) throw new BoundaryViolationException("No parent"); BTPos vv = checkPosition(v); return T.get(vv.index()/2); } /** Replaces the element at v. */ public E replace(Position v, E o) throws InvalidPositionException { BTPos vv = checkPosition(v); return vv.setElement(o); } /** Adds an element just after the last node (in a level numbering). */ public Position add(E e) { int i = size() + 1; BTPos p = new BTPos(e,i); T.add(i, p); return p; } /** Removes and returns the element at the last node. */ public E remove() throws EmptyTreeException { if(isEmpty()) throw new EmptyTreeException("Tree is empty"); return T.remove(size()).element(); } /** Determines whether the given position is a valid node. */ protected BTPos checkPosition(Position v) throws InvalidPositionException { if (v == null || !(v instanceof BTPos)) throw new InvalidPositionException("Position is invalid"); return (BTPos) v; } /** Returns an iterator of the elements stored at all nodes in the tree. */ public Iterator iterator() { ArrayList list = new ArrayList(); Iterator> iter = T.iterator(); iter.next(); // skip the first element while (iter.hasNext()) list.add(iter.next().element()); return list.iterator(); } }