// Textbook fragment 07.19 /** Removes a node with zero or one child. */ public E remove(Position v) throws InvalidPositionException { BTPosition vv = checkPosition(v); BTPosition leftPos = vv.getLeft(); BTPosition rightPos = vv.getRight(); if (leftPos != null && rightPos != null) throw new InvalidPositionException("Cannot remove node with two children") ; BTPosition ww; // the only child of v, if any if (leftPos != null) ww = leftPos; else if (rightPos != null) ww = rightPos; else // v is a leaf ww = null; if (vv == root) { // v is the root if (ww != null) ww.setParent(null); root = ww; } else { // v is not the root BTPosition uu = vv.getParent(); if (vv == uu.getLeft()) uu.setLeft(ww); else uu.setRight(ww); if(ww != null) ww.setParent(uu); } size--; return v.element(); }