BSTInserter.java
Created with JBuilder

package brs.visitor;

import brs.*;
import ordering.*;

/**
* Inserts an IOrdered into the host maintaining the host's binary search tree
* property.
* Duplication is not allowed: replaces old data object with the new one.

Suppose we have a set of objects that can be compared for equality with "equal to" and "totally ordered" with an order relation called "less or equal to" . Define "less than" to mean "less or equal to" AND "not equal to". Let T be a BiTree structure that stores such totally ordered objects.

Definition:
T is said to satisfy the binary search tree property (BSTP) if
  T is empty, or
  when T is not empty, the left and right subtrees of T both satisfy BSTP, and
  all elements in the left subtree of T are less than the root of T, and
  the root of T is less than all elements in the right subtree of T.
* @author Dung X. Nguyen - Copyright 2001 - All rights reserved. */ public class BSTInserter implements IVisitor { private AOrder _order; public BSTInserter (AOrder order) { _order = order; } /** * Returns the host tree where the input is inserted as the root. * @param host an empty binary tree, which obviously satisfies BSTP. * @param input new data to be inserted. * @return host (which is no longer empty). */ public Object emptyCase(BiTree host, Object input) { host.insertRoot (input); return host; } /** * If order.eq (input, host.getRootDat) then the old root data is replaced * by input. * @param host non-empty and satisfies BSTP. * @param input new data to be inserted. * @return the tree where input is inserted as the root. */ 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)) { host.setRootDat(input); return host; } return host.getRightSubTree().execute(this, input); } }
BSTInserter.java
Created with JBuilder