Code Fragment: BST4



public:
  void removeElement(const Key& k)			// remove using key
      throw(NonexistentElementException) {
    BTPosition p = finder(k, T.root());			// find the node
    if (p.isNull())					// not found?
      throw NonexistentElementException("Remove nonexistent element");
    remover(p);						// remove it
  }
protected:
  BTPosition remover(const BTPosition& r) {		// remove utility
    BTPosition p;
    if (T.isExternal(T.leftChild(r)))			// left is external?
      p = T.leftChild(r);				// remove from left
    else if (T.isExternal(T.rightChild(r)))		// right is external?
      p = T.rightChild(r);				// remove from right
    else {						// both internal?
      p = T.rightChild(r);				// p = replacement
      do 						// find leftmost in
        p = T.leftChild(p);				// ...right subtree
      while (T.isInternal(p));
      setItem(r, T.parent(p).element());		// copy parent(p) to r
    }
    return T.removeAboveExternal(p);			// remove p and parent
  }