BSTDeleter.java
Created with JBuilder

package brs.visitor;

import brs.*;
import ordering.*;

/**
* Deletes the given input from the host tree.
* 
   Invariant: host contains unique objects and satisfies the BST property.
   Post: host does not contains the input.
   Algorithm:
   Case host is empty:
      returns null because there is nothing to remove.
   Case host is not empty:
      if input < root
          ask the host's left subtree to delete the input;
      else if root < input
          ask the host's right subtree to delete the input
      else (at this point, input == root)
      if host is a leaf
          ask the host to remove its root;
      else if host's left subtree is empty (i.e. right subtree is NOT empty) {
         ask host to replace the root with the minimum value of its right subtree;
         ask host's right subtree to delete this minimum value;
      }
      else (at this point, the left subtree must NOT be empty)  {
         ask host to replace the root with the maximum value of its left subtree;
         ask host's right subtree to delete this maximum value;
      }
   

NOTE: In the above algorithm, the case when host is a leaf can be implemented in many ways. One way is to check for the emptiness of the subtrees. As you have been indoctrinated, it is "impolite" do ask something for what it is. So we ask the subtrees to help do the deletion instead. * @author Dung X. Nguyen * @since 11/06/01 Copyright 2000 - All rights reserved. */ public class BSTDeleter implements IVisitor { private AOrder _order; public BSTDeleter (AOrder order) { _order = order; } /** * Returns null. * @param host is empty and obviously satisfies the BST Property. * @param input not used * @return null */ public Object emptyCase(BiTree host, Object input) { return null; } /** *

    if input < root
      ask the host's left subtree to delete the input;
    else if root < input
      ask the host's right subtree to delete the input
    else (at this point, input == root)
      pass the host to its left subtree and ask it to help to remove the host's root;
    
* @param host non-empty and satifies BST property * @param input object to be deleted from the host. * @return null. */ public Object nonEmptyCase(BiTree host, Object input) { Object root = host.getRootDat(); if (_order.lt(input, root)) { return host.getLeftSubTree().execute (this, input); } if (_order.eq (input, root)) { return host.getLeftSubTree().execute(new LeftDeleter(host, this), null); } return host.getRightSubTree().execute (this, input); } }
BSTDeleter.java
Created with JBuilder