// Textbook fragment 07.20 /** Attaches two trees to be subtrees of an external node. */ public void attach(Position v, BinaryTree T1, BinaryTree T2) throws InvalidPositionException { BTPosition vv = checkPosition(v); if (isInternal(v)) throw new InvalidPositionException("Cannot attach from internal node"); if (!T1.isEmpty()) { BTPosition r1 = checkPosition(T1.root()); vv.setLeft(r1); r1.setParent(vv); // T1 should be invalidated } if (!T2.isEmpty()) { BTPosition r2 = checkPosition(T2.root()); vv.setRight(r2); r2.setParent(vv); // T2 should be invalidated } } /** If v is a good binary tree node, cast to BTPosition, else throw exception */ protected BTPosition checkPosition(Position v) throws InvalidPositionException { if (v == null || !(v instanceof BTPosition)) throw new InvalidPositionException("The position is invalid"); return (BTPosition) v; } /** Creates a new binary tree node */ protected BTPosition createNode(E element, BTPosition parent, BTPosition left, BTPosition right) { return new BTNode(element,parent,left,right); } /** Creates a list storing the the nodes in the subtree of a node, * ordered according to the preorder traversal of the subtree. */ protected void preorderPositions(Position v, PositionList> pos) throws InvalidPositionException { pos.addLast(v); if (hasLeft(v)) preorderPositions(left(v), pos); // recurse on left child if (hasRight(v)) preorderPositions(right(v), pos); // recurse on right child }