Source of 26.18.java


  1: // @author Frank M. Carrano, Timothy M. Henry
  2: // @version 5.0

  4: private T addEntry(T anEntry)
  5: {
  6:    BinaryNode<T> currentNode = getRootNode();
  7:    // Assertion: currentNode != null
  8:    T result = null;
  9:    boolean found = false;

 11:    while (!found)
 12:    {
 13:       T currentEntry = currentNode.getData();
 14:       int comparison = anEntry.compareTo(currentEntry);

 16:       if (comparison == 0)
 17:       {  // anEntry matches currentEntry;
 18:          // return and replace currentEntry
 19:          found = true;
 20:          result = currentEntry;
 21:          currentNode.setData(anEntry);
 22:       }
 23:       else if (comparison < 0)
 24:       {
 25:          if (currentNode.hasLeftChild())
 26:             currentNode = currentNode.getLeftChild();
 27:          else
 28:          {
 29:             found = true;
 30:             currentNode.setLeftChild(new BinaryNode<>(anEntry));
 31:          } // end if
 32:       }
 33:       else
 34:       {
 35:          // Assertion: comparison > 0

 37:          if (currentNode.hasRightChild())
 38:             currentNode = currentNode.getRightChild();
 39:          else
 40:          {
 41:             found = true;
 42:             currentNode.setRightChild(new BinaryNode<>(anEntry));
 43:          } // end if
 44:       } // end if
 45:    } // end while

 47:    return result;
 48: } // end addEntry