SlideShare a Scribd company logo
1 of 20
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 BST Augmentations

Binary Tree
Binary  TreeBinary  Tree
Binary TreeVishal Gaur
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docxjeanettehully
 
package DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdfpackage DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdfapleathers
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3infanciaj
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfankit11134
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxshericehewat
 
Use the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docxUse the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docxdickonsondorris
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxAssg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxfestockton
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfadityastores21
 
Describe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdfDescribe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdfrajeshjain2109
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxfestockton
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxrock73
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfwasemanivytreenrco51
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfannaelctronics
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdfarshin9
 

Similar to BST Augmentations (20)

Binary Tree
Binary  TreeBinary  Tree
Binary Tree
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docx
 
package DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdfpackage DataStructures; public class HelloWorld AnyType extends.pdf
package DataStructures; public class HelloWorld AnyType extends.pdf
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
 
Given the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docxGiven the following ADT definition of a stack to use stack .docx
Given the following ADT definition of a stack to use stack .docx
 
Use the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docxUse the following data set that compares age to average years lef.docx
Use the following data set that compares age to average years lef.docx
 
611+tutorial
611+tutorial611+tutorial
611+tutorial
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxAssg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
Describe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdfDescribe a data structure to represent sets of elements (each element.pdf
Describe a data structure to represent sets of elements (each element.pdf
 
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docxAssg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
Assg 12 Binary Search Trees COSC 2336assg-12.cppAssg 12 Binary .docx
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docxAvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
 
List
ListList
List
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 
On the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdfOn the code which has a class in which I implementing a binary tree .pdf
On the code which has a class in which I implementing a binary tree .pdf
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 

More from debishakespeare

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

More from debishakespeare (20)

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

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

BST Augmentations

  • 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. } }