SlideShare a Scribd company logo
Required to augment the author's Binary Search Tree (BST)
code to support these new operations. Method names below are
merely suggestions. (The author’s class is attached separately in
the file called “authordoc”. I just built a simple test tree in the
author’s main method which can be used to test the various
operations. )
1. AnyType nthElement(int n) -- returns the n-th element
(starting from 1) of the in-order traversal of the BST.
2. int rank( AnyType x ) -- returns the "rank" of x. The rank of
an element is its position (starting with 1) in an in-order
traversal.
3. AnyType median( ) -- returns the median (middle) element in
the BST. If the BST contains an even number of elements,
returns the smaller of the two medians.
4. boolean isPerfect( ) -- returns true if the BST is a perfect
binary tree.
5. boolean isComplete( ) -- returns true if the BST is a complete
binary tree.
6. String toString( int nrLevels ) -- generates the level-order
output described in the sample output below.
Most of these operations could easily be implemented by
performing an in-order traversal inside the BST and perhaps
placing the results in an ArrayList. However, such a method is
extremely inefficient. Instead, we are going to achieve faster
performance by "augmenting" the BST nodes. You will add a
new private integer data member ("tree size") to the BinaryNode
which stores the size of the tree rooted at that node (including
the root). You must develop your own algorithms for these
operations, but obviously you will use the new tree size data
member to guide your search. Think before you code and think
recursively!
These items cover those topics not addressed elsewhere in the
project description. (R) indicates a requirement, (H) indicates a
hint, and (N) indicates a note.
1. (R) Although we are only using the BST for integers, the BST
must remain a generic class.
2. (R) Duplicate values are not allowed. Attempts to insert a
duplicate value should be ignored.
3. (R) Attempts to remove non-existent values should be
ignored.
4. (R) From a coding perspective, the easiest way to avoid
duplicate insertions or attempting to remove non-existent
elements is to first call find( ). However, this technique is NOT
permitted for two reasons.
Calling find( ) before each insert/remove doubles the running
time for these operations and is therefore inefficient.
Recusively coding the insert/remove methods to handle these
situations is a great learning experience.
5. (R) The level order print (PRINT command) outputs the
value of each node, the size of the tree rooted at that node, and
the value of the node's parent in that order, inside parenthesis,
separated by commas. (node value, tree size, parent value).
Since the root has no parent, print NULL for the root's parent
value. For readability, separate the levels with a blank line and
print no more than 6 node/size/parent values per line. If a level
requires multiple lines, use consecutive lines (without a blank
line between them).
6. (R) Efficieny counts! Use the most efficient algorithm
possible In particular, don't make multiple searches in the tree
when one will do. (Yes, we know it doesn't matter from an
asymptotic analysis point of view.)
7. (H) Almost all of these operations should be written
recursively, but not necessarily all of them.
8. (N) As is customary, your BST class should not provide any
methods for printing. However, the BST can provide a method
that formats a string containing information that the user wishes
to print. Overloading the toString( ) method is a common
technique to achieve this kind of functionality.
Note: The instructor noted that once the tree is built, it will not
be changed during testing of the program. (just to simplify the
task if that helps)
package Ast.rt;
import java.util.ArrayList;
// BinarySearchTree class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC
OPERATIONS*********************
// void insert( x ) --> Insert x
// void remove( x ) --> Remove x
// boolean contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// void printTree( ) --> Print tree in sorted order
//
******************ERRORS***************************
*****
// Throws UnderflowException as appropriate
/**
* Implements an unbalanced binary search tree.
* Note that all "matching" is based on the compareTo method.
* @author Mark Allen Weiss
*/
public class BinarySearchTree<AnyType extends Comparable<?
super AnyType>>
{
/**
* Construct the tree.
*/
public BinarySearchTree( )
{
root = null;
}
/**
* Insert into the tree; duplicates are ignored.
* @param x the item to insert.
*/
public void insert( AnyType x )
{
root = insert( x, root );
}
/**
* Remove from the tree. Nothing is done if x is not found.
* @param x the item to remove.
*/
public void remove( AnyType x )
{
root = remove( x, root );
}
/**
* Find the smallest item in the tree.
* @return smallest item or null if empty.
* @throws Exception
*/
public AnyType findMin( ) throws Exception
{
if( isEmpty( ) )
throw new Exception( );
return findMin( root ).element;
}
/**
* Find the largest item in the tree.
* @return the largest item of null if empty.
* @throws Exception
*/
public AnyType findMax( ) throws Exception
{
if( isEmpty( ) )
throw new Exception( );
return findMax( root ).element;
}
/**
* Find an item in the tree.
* @param x the item to search for.
* @return true if not found.
*/
public boolean contains( AnyType x )
{
return contains( x, root );
}
/**
* Make the tree logically empty.
*/
public void makeEmpty( )
{
root = null;
}
/**
* Test if the tree is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( )
{
return root == null;
}
/**
* Print the tree contents in sorted order.
*/
public void printTree( )
{
if( isEmpty( ) )
System.out.println( "Empty tree" );
else
printTree( root );
}
/**
* Internal method to insert into a subtree.
* @param x the item to insert.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> insert( AnyType x,
BinaryNode<AnyType> t )
{
if( t == null )
return new BinaryNode<AnyType>( x, null, null);
int compareResult = x.compareTo( t.element );
if( compareResult < 0 ){
t.left = insert( x, t.left );
}
else if( compareResult > 0 ){
t.right = insert( x, t.right );
}
else
; // Duplicate; do nothing
return t;
}
/**
* Internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the subtree.
* @return the new root of the subtree.
*/
private BinaryNode<AnyType> remove( AnyType x,
BinaryNode<AnyType> t )
{
if( t == null )
return t; // Item not found; do nothing
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
t.left = remove( x, t.left );
else if( compareResult > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.element = findMin( t.right ).element;
t.right = remove( t.element, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}
/**
* Internal method to find the smallest item in a subtree.
* @param t the node that roots the subtree.
* @return node containing the smallest item.
*/
private BinaryNode<AnyType> findMin(
BinaryNode<AnyType> t )
{
if( t == null )
return null;
else if( t.left == null )
return t;
return findMin( t.left );
}
/**
* Internal method to find the largest item in a subtree.
* @param t the node that roots the subtree.
* @return node containing the largest item.
*/
private BinaryNode<AnyType> findMax(
BinaryNode<AnyType> t )
{
if( t != null )
while( t.right != null )
t = t.right;
return t;
}
/**
* Internal method to find an item in a subtree.
* @param x is item to search for.
* @param t the node that roots the subtree.
* @return node containing the matched item.
*/
private boolean contains( AnyType x,
BinaryNode<AnyType> t )
{
if( t == null )
return false;
int compareResult = x.compareTo( t.element );
if( compareResult < 0 )
return contains( x, t.left );
else if( compareResult > 0 )
return contains( x, t.right );
else
return true; // Match
}
/**
* Internal method to print a subtree in sorted order.
* @param t the node that roots the subtree.
*/
private void printTree( BinaryNode<AnyType> t )
{
if( t != null )
{
printTree( t.left );
System.out.println( t.element );
printTree( t.right );
}
}
/**
* Internal method to compute height of a subtree.
* @param t the node that roots the subtree.
*/
private int height( BinaryNode<AnyType> t )
{
if( t == null )
return -1;
else
return 1 + Math.max( height( t.left ), height( t.right ) );
}
// Basic node stored in unbalanced binary search trees
private static class BinaryNode<AnyType>
{
// Constructors
BinaryNode( AnyType theElement )
{
this( theElement, null, null);
}
BinaryNode( AnyType theElement,
BinaryNode<AnyType> lt, BinaryNode<AnyType> rt)
{
element = theElement;
left = lt;
right = rt;
}
AnyType element; // The data in the node
BinaryNode<AnyType> left; // Left child
BinaryNode<AnyType> right; // Right child
int treeSize;
}
/** The tree root. */
private BinaryNode<AnyType> root;
// Test program
public static void main( String [ ] args ) throws Exception
{
BinarySearchTree<Integer> t = new
BinarySearchTree<Integer>( );
int[] nums = new int[] {55, 40, 60, 30, 45, 70, 20, 35, 44,
47, 66, 80, 3, 36, 37, 43, 48, 65, 67, 77, 90};
for(int i = 0; i < nums.length; i++)
t.insert(nums[i]);
t.printTree();
System.out.println( "Checking... (no more output means
success)" );
}
}

More Related Content

Similar to Required to augment the authors Binary Search Tree (BST) code to .docx (20)

DOCX
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
olsenlinnea427
 
PDF
Write a C++ program that implements a binary search tree (BST) to man.pdf
hardjasonoco14599
 
PDF
Binary Tree
Vishal Gaur
 
PDF
Write a program that accepts an arithmetic expression of unsigned in.pdf
JUSTSTYLISH3B2MOHALI
 
DOCX
Running Head Discussion Board .docx
jeanettehully
 
PDF
package DataStructures; public class HelloWorld AnyType extends.pdf
apleathers
 
PPTX
data structures and algorithms Unit 3
infanciaj
 
PDF
Please help solve this in C++ So the program is working fin.pdf
ankit11134
 
DOCX
Use the following data set that compares age to average years lef.docx
dickonsondorris
 
DOCX
611+tutorial
Prudence Mashile
 
DOCX
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
festockton
 
PDF
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
PDF
Describe a data structure to represent sets of elements (each element.pdf
rajeshjain2109
 
DOCX
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
festockton
 
DOCX
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
rock73
 
PDF
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
arihantelehyb
 
PPT
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
 
PPT
List
Amit Vats
 
PDF
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
JAVA - Design a data structure IntSet that can hold a set of integers-.docx
olsenlinnea427
 
Write a C++ program that implements a binary search tree (BST) to man.pdf
hardjasonoco14599
 
Binary Tree
Vishal Gaur
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
JUSTSTYLISH3B2MOHALI
 
Running Head Discussion Board .docx
jeanettehully
 
package DataStructures; public class HelloWorld AnyType extends.pdf
apleathers
 
data structures and algorithms Unit 3
infanciaj
 
Please help solve this in C++ So the program is working fin.pdf
ankit11134
 
Use the following data set that compares age to average years lef.docx
dickonsondorris
 
611+tutorial
Prudence Mashile
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
festockton
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
Describe a data structure to represent sets of elements (each element.pdf
rajeshjain2109
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
festockton
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
rock73
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
arihantelehyb
 
FRbsbsvvsvsvbshgsgsvzvsvvsvsvsvsvsvvev.ppt
hassannadim591
 
List
Amit Vats
 
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 

More from debishakespeare (20)

DOCX
Ethical Case Study 2Gloria is a housekeeper in an independent li.docx
debishakespeare
 
DOCX
Ethical consideration is important in nursing practice, especial.docx
debishakespeare
 
DOCX
Ethical Competency Writing Assignment DescriptionPHI 108 Spr.docx
debishakespeare
 
DOCX
Ethical Case StudyAn example of unethical treatment of participa.docx
debishakespeare
 
DOCX
Ethical AwarenessDEFINITION a brief definition of the k.docx
debishakespeare
 
DOCX
ETHICAL CHALLENGES JOYCAROLYNE MUIGAINTC3025262020.docx
debishakespeare
 
DOCX
Ethical Conduct of Researchpower point from this document, 1.docx
debishakespeare
 
DOCX
Ethical Challenges and Agency IssuesI.IntroductionII.E.docx
debishakespeare
 
DOCX
Ethical Approaches An Overview of .docx
debishakespeare
 
DOCX
Ethical and Professional Issues in Group PracticeThose who seek .docx
debishakespeare
 
DOCX
Ethical AnalysisSelect a work-related ethical scenario that .docx
debishakespeare
 
DOCX
Ethical (Moral) RelativismIn America, many are comfortable describ.docx
debishakespeare
 
DOCX
Ethical Analysis on Lehman Brothers financial crisis of 2008 , pleas.docx
debishakespeare
 
DOCX
Ethical Analysis on Merrill lynch financial crisis of 2008 , please .docx
debishakespeare
 
DOCX
ETHC 101Discussion Board Reply Grading RubricCriteriaLevels .docx
debishakespeare
 
DOCX
Ethical and Human Rights Concerns in Global HealthChapter Fou.docx
debishakespeare
 
DOCX
Ethical & Legal Aspects in Nursing WK 14Please answer the .docx
debishakespeare
 
DOCX
EthernetSatellite dishInternational Plastics, Inc. - C.docx
debishakespeare
 
DOCX
Ethanolv.DrizinUnited States District Court, N.D. Iowa, Eastern .docx
debishakespeare
 
DOCX
Ethan FromeEdith WhartonTHE EMC MASTERPIECE SERIES.docx
debishakespeare
 
Ethical Case Study 2Gloria is a housekeeper in an independent li.docx
debishakespeare
 
Ethical consideration is important in nursing practice, especial.docx
debishakespeare
 
Ethical Competency Writing Assignment DescriptionPHI 108 Spr.docx
debishakespeare
 
Ethical Case StudyAn example of unethical treatment of participa.docx
debishakespeare
 
Ethical AwarenessDEFINITION a brief definition of the k.docx
debishakespeare
 
ETHICAL CHALLENGES JOYCAROLYNE MUIGAINTC3025262020.docx
debishakespeare
 
Ethical Conduct of Researchpower point from this document, 1.docx
debishakespeare
 
Ethical Challenges and Agency IssuesI.IntroductionII.E.docx
debishakespeare
 
Ethical Approaches An Overview of .docx
debishakespeare
 
Ethical and Professional Issues in Group PracticeThose who seek .docx
debishakespeare
 
Ethical AnalysisSelect a work-related ethical scenario that .docx
debishakespeare
 
Ethical (Moral) RelativismIn America, many are comfortable describ.docx
debishakespeare
 
Ethical Analysis on Lehman Brothers financial crisis of 2008 , pleas.docx
debishakespeare
 
Ethical Analysis on Merrill lynch financial crisis of 2008 , please .docx
debishakespeare
 
ETHC 101Discussion Board Reply Grading RubricCriteriaLevels .docx
debishakespeare
 
Ethical and Human Rights Concerns in Global HealthChapter Fou.docx
debishakespeare
 
Ethical & Legal Aspects in Nursing WK 14Please answer the .docx
debishakespeare
 
EthernetSatellite dishInternational Plastics, Inc. - C.docx
debishakespeare
 
Ethanolv.DrizinUnited States District Court, N.D. Iowa, Eastern .docx
debishakespeare
 
Ethan FromeEdith WhartonTHE EMC MASTERPIECE SERIES.docx
debishakespeare
 
Ad

Recently uploaded (20)

PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PDF
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
PPTX
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
SSHS-2025-PKLP_Quarter-1-Dr.-Kerby-Alvarez.pdf
AishahSangcopan1
 
HYDROCEPHALUS: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
LAW OF CONTRACT ( 5 YEAR LLB & UNITARY LLB)- MODULE-3 - LEARN THROUGH PICTURE
APARNA T SHAIL KUMAR
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
Ad

Required to augment the authors Binary Search Tree (BST) code to .docx

  • 1. Required to augment the author's Binary Search Tree (BST) code to support these new operations. Method names below are merely suggestions. (The author’s class is attached separately in the file called “authordoc”. I just built a simple test tree in the author’s main method which can be used to test the various operations. ) 1. AnyType nthElement(int n) -- returns the n-th element (starting from 1) of the in-order traversal of the BST. 2. int rank( AnyType x ) -- returns the "rank" of x. The rank of an element is its position (starting with 1) in an in-order traversal. 3. AnyType median( ) -- returns the median (middle) element in the BST. If the BST contains an even number of elements, returns the smaller of the two medians. 4. boolean isPerfect( ) -- returns true if the BST is a perfect binary tree. 5. boolean isComplete( ) -- returns true if the BST is a complete binary tree. 6. String toString( int nrLevels ) -- generates the level-order output described in the sample output below. Most of these operations could easily be implemented by performing an in-order traversal inside the BST and perhaps placing the results in an ArrayList. However, such a method is extremely inefficient. Instead, we are going to achieve faster performance by "augmenting" the BST nodes. You will add a new private integer data member ("tree size") to the BinaryNode which stores the size of the tree rooted at that node (including the root). You must develop your own algorithms for these operations, but obviously you will use the new tree size data member to guide your search. Think before you code and think recursively! These items cover those topics not addressed elsewhere in the project description. (R) indicates a requirement, (H) indicates a
  • 2. hint, and (N) indicates a note. 1. (R) Although we are only using the BST for integers, the BST must remain a generic class. 2. (R) Duplicate values are not allowed. Attempts to insert a duplicate value should be ignored. 3. (R) Attempts to remove non-existent values should be ignored. 4. (R) From a coding perspective, the easiest way to avoid duplicate insertions or attempting to remove non-existent elements is to first call find( ). However, this technique is NOT permitted for two reasons. Calling find( ) before each insert/remove doubles the running time for these operations and is therefore inefficient. Recusively coding the insert/remove methods to handle these situations is a great learning experience. 5. (R) The level order print (PRINT command) outputs the value of each node, the size of the tree rooted at that node, and the value of the node's parent in that order, inside parenthesis, separated by commas. (node value, tree size, parent value). Since the root has no parent, print NULL for the root's parent value. For readability, separate the levels with a blank line and print no more than 6 node/size/parent values per line. If a level requires multiple lines, use consecutive lines (without a blank line between them). 6. (R) Efficieny counts! Use the most efficient algorithm possible In particular, don't make multiple searches in the tree when one will do. (Yes, we know it doesn't matter from an asymptotic analysis point of view.) 7. (H) Almost all of these operations should be written recursively, but not necessarily all of them. 8. (N) As is customary, your BST class should not provide any methods for printing. However, the BST can provide a method that formats a string containing information that the user wishes to print. Overloading the toString( ) method is a common technique to achieve this kind of functionality.
  • 3. Note: The instructor noted that once the tree is built, it will not be changed during testing of the program. (just to simplify the task if that helps) package Ast.rt; import java.util.ArrayList; // BinarySearchTree class // // CONSTRUCTION: with no initializer // // ******************PUBLIC OPERATIONS********************* // void insert( x ) --> Insert x // void remove( x ) --> Remove x // boolean contains( x ) --> Return true if x is present // Comparable findMin( ) --> Return smallest item
  • 4. // Comparable findMax( ) --> Return largest item // boolean isEmpty( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // void printTree( ) --> Print tree in sorted order // ******************ERRORS*************************** ***** // Throws UnderflowException as appropriate /** * Implements an unbalanced binary search tree. * Note that all "matching" is based on the compareTo method. * @author Mark Allen Weiss */ public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> { /** * Construct the tree. */
  • 5. public BinarySearchTree( ) { root = null; } /** * Insert into the tree; duplicates are ignored. * @param x the item to insert. */ public void insert( AnyType x ) { root = insert( x, root ); } /** * Remove from the tree. Nothing is done if x is not found. * @param x the item to remove. */
  • 6. public void remove( AnyType x ) { root = remove( x, root ); } /** * Find the smallest item in the tree. * @return smallest item or null if empty. * @throws Exception */ public AnyType findMin( ) throws Exception { if( isEmpty( ) ) throw new Exception( ); return findMin( root ).element;
  • 7. } /** * Find the largest item in the tree. * @return the largest item of null if empty. * @throws Exception */ public AnyType findMax( ) throws Exception { if( isEmpty( ) ) throw new Exception( ); return findMax( root ).element; } /** * Find an item in the tree. * @param x the item to search for. * @return true if not found.
  • 8. */ public boolean contains( AnyType x ) { return contains( x, root ); } /** * Make the tree logically empty. */ public void makeEmpty( ) { root = null; } /** * Test if the tree is logically empty. * @return true if empty, false otherwise. */
  • 9. public boolean isEmpty( ) { return root == null; } /** * Print the tree contents in sorted order. */ public void printTree( ) { if( isEmpty( ) ) System.out.println( "Empty tree" ); else printTree( root ); } /** * Internal method to insert into a subtree.
  • 10. * @param x the item to insert. * @param t the node that roots the subtree. * @return the new root of the subtree. */ private BinaryNode<AnyType> insert( AnyType x, BinaryNode<AnyType> t ) { if( t == null ) return new BinaryNode<AnyType>( x, null, null); int compareResult = x.compareTo( t.element ); if( compareResult < 0 ){ t.left = insert( x, t.left ); } else if( compareResult > 0 ){ t.right = insert( x, t.right );
  • 11. } else ; // Duplicate; do nothing return t; } /** * Internal method to remove from a subtree. * @param x the item to remove. * @param t the node that roots the subtree. * @return the new root of the subtree. */ private BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t ) { if( t == null ) return t; // Item not found; do nothing int compareResult = x.compareTo( t.element );
  • 12. if( compareResult < 0 ) t.left = remove( x, t.left ); else if( compareResult > 0 ) t.right = remove( x, t.right ); else if( t.left != null && t.right != null ) // Two children { t.element = findMin( t.right ).element; t.right = remove( t.element, t.right ); } else t = ( t.left != null ) ? t.left : t.right; return t; } /** * Internal method to find the smallest item in a subtree. * @param t the node that roots the subtree.
  • 13. * @return node containing the smallest item. */ private BinaryNode<AnyType> findMin( BinaryNode<AnyType> t ) { if( t == null ) return null; else if( t.left == null ) return t; return findMin( t.left ); } /** * Internal method to find the largest item in a subtree. * @param t the node that roots the subtree. * @return node containing the largest item. */ private BinaryNode<AnyType> findMax( BinaryNode<AnyType> t )
  • 14. { if( t != null ) while( t.right != null ) t = t.right; return t; } /** * Internal method to find an item in a subtree. * @param x is item to search for. * @param t the node that roots the subtree. * @return node containing the matched item. */ private boolean contains( AnyType x, BinaryNode<AnyType> t ) {
  • 15. if( t == null ) return false; int compareResult = x.compareTo( t.element ); if( compareResult < 0 ) return contains( x, t.left ); else if( compareResult > 0 ) return contains( x, t.right ); else return true; // Match } /** * Internal method to print a subtree in sorted order. * @param t the node that roots the subtree. */ private void printTree( BinaryNode<AnyType> t )
  • 16. { if( t != null ) { printTree( t.left ); System.out.println( t.element ); printTree( t.right ); } } /** * Internal method to compute height of a subtree. * @param t the node that roots the subtree. */ private int height( BinaryNode<AnyType> t ) { if( t == null ) return -1; else
  • 17. return 1 + Math.max( height( t.left ), height( t.right ) ); } // Basic node stored in unbalanced binary search trees private static class BinaryNode<AnyType> { // Constructors BinaryNode( AnyType theElement ) { this( theElement, null, null); } BinaryNode( AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt) { element = theElement; left = lt;
  • 18. right = rt; } AnyType element; // The data in the node BinaryNode<AnyType> left; // Left child BinaryNode<AnyType> right; // Right child int treeSize; } /** The tree root. */ private BinaryNode<AnyType> root;
  • 19. // Test program public static void main( String [ ] args ) throws Exception { BinarySearchTree<Integer> t = new BinarySearchTree<Integer>( ); int[] nums = new int[] {55, 40, 60, 30, 45, 70, 20, 35, 44, 47, 66, 80, 3, 36, 37, 43, 48, 65, 67, 77, 90}; for(int i = 0; i < nums.length; i++) t.insert(nums[i]); t.printTree(); System.out.println( "Checking... (no more output means success)" );
  • 20. } }