SlideShare ist ein Scribd-Unternehmen logo
1 von 7
Downloaden Sie, um offline zu lesen
Create a class BinarySearchTree. A class that implements the ADT binary search tree by
extending BinaryTree. Recursive version.
public class BinarySearchTree<T extends Comparable<? super T>>
extends BinaryTree<T> implements SearchTreeInterface<T>
{
public BinarySearchTree ()
{
super();
} // end default constructor
public BinarySearchTree (T rootEntry)
{
super();
setRootNode(new BinaryNode<>(rootEntry));
} // end constructor
public void setTree (T rootData) // Disable setTree (see Segment 25.6)
{
throw new UnsupportedOperationException();
} // end setTree
public void setTree (T rootData, BinaryTreeInterface<T> leftTree, BinaryTreeInterface<T>
rightTree)
{
throw new UnsupportedOperationException();
} // end setTree
//...
public T remove (T entry)
{
ReturnObject oldEntry = new ReturnObject(null);
BinaryNode<T> newRoot = removeEntry(getRootNode(), entry, oldEntry);
setRootNode(newRoot);
return oldEntry.get();
} // end remove
//...
private class ReturnObject
{
private T item;
private ReturnObject(T entry)
{
item = entry;
} // end constructor
public T get()
{
return item;
} // end get
public void set(T entry)
{
item = entry;
} // end set
} // end ReturnObject
} // end BinarySearchTree
HERE IS BinaryTree.java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class BinaryTree<T> implements BinaryTreeInterface<T> {
private BinaryNode<T> root;
public BinaryTree() {
root = null;
}
public BinaryTree(T rootData) {
root = new BinaryNode<>(rootData);
}
public BinaryTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree) {
privateSetTree(rootData, leftTree, rightTree);
}
private void privateSetTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T>
rightTree) {
root = new BinaryNode<>(rootData);
if (leftTree != null && !leftTree.isEmpty()) {
root.setLeftChild(leftTree.root);
}
if (rightTree != null && !rightTree.isEmpty()) {
if (rightTree != leftTree) {
root.setRightChild(rightTree.root);
} else {
root.setRightChild(rightTree.root.copy());
}
}
if (leftTree != null && leftTree != this) {
leftTree.clear();
}
if (rightTree != null && rightTree != this) {
rightTree.clear();
}
}
@Override
public T getRootData() {
if (isEmpty()) {
throw new EmptyTreeException("The tree is empty.");
}
return root.getData();
}
@Override
public int getHeight() {
return root.getHeight();
}
@Override
public int getNumberOfNodes() {
return root.getNumberOfNodes();
}
@Override
public boolean isEmpty() {
return root == null;
}
@Override
public void clear() {
root = null;
}
@Override
public Iterator<T> getPreorderIterator() {
return new PreorderIterator();
}
@Override
public Iterator<T> getInorderIterator() {
return new InorderIterator();
}
@Override
public Iterator<T> getPostorderIterator() {
return new PostorderIterator();
}
private class PreorderIterator implements Iterator<T> {
private StackInterface<BinaryNode<T>> nodeStack;
public PreorderIterator() {
nodeStack = new LinkedStack<>();
if (root != null) {
nodeStack.push(root);
}
}
public boolean hasNext() {
return !nodeStack.isEmpty();
}
public T next() {
BinaryNode<T> nextNode;
if (hasNext()) {
nextNode = nodeStack.pop();
BinaryNode<T> leftChild = nextNode.getLeftChild();
BinaryNode<T> rightChild = nextNode.getRightChild();
if (rightChild != null) {
nodeStack.push(rightChild);
}
if (leftChild != null) {
nodeStack.push(leftChild);
}
} else {
throw new NoSuchElementException();
}
return nextNode.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private class InorderIterator implements Iterator<T> {
private StackInterface<BinaryNode<T>> nodeStack;
private BinaryNode<T> currentNode;
public InorderIterator() {
nodeStack = new LinkedStack<>();
currentNode = root;
}
public boolean hasNext() {
return !nodeStack.isEmpty() || (currentNode != null);
}
public T next() {
BinaryNode<T> nextNode = null;
while (currentNode !=null) {
nodeStack.push(currentNode);
currentNode = currentNode.getLeftChild();
}
if (!nodeStack.isEmpty()) {
nextNode = nodeStack.pop();
currentNode = nextNode.getRightChild();
} else {
throw new NoSuchElementException();
}
return nextNode.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
private class PostorderIterator implements Iterator<T> {
private StackInterface<BinaryNode<T>> nodeStack;
private BinaryNode<T> currentNode;
private BinaryNode<T> lastNodeVisited;
public PostorderIterator() {
nodeStack = new LinkedStack<>();
currentNode = root;
lastNodeVisited = null;
}
public boolean hasNext() {
return !nodeStack.isEmpty() || (currentNode != null);
}
public T next() {
BinaryNode<T> leftChild, rightChild, nextNode = null;
while (currentNode != null) {
nodeStack.push(currentNode);
leftChild = currentNode.getLeftChild();
if (leftChild == null) {
currentNode = currentNode.getRightChild();
} else {
currentNode = leftChild;
}
}
// stack is not empty, pop top node
if (!nodeStack.isEmpty()) {
nextNode = nodeStack.pop();
BinaryNode<T> parent = null;
if (!nodeStack.isEmpty()) {
parent = nodeStack.peek();
if (nextNode == parent.getLeftChild()) {
currentNode = parent.getRightChild();
} else {
currentNode = null;
}
} else {
currentNode = null;
}
} else {
throw new NoSuchElementException();
}
return nextNode.getData();
}
public void remove() {
throw new UnsupportedOperationException();
}//end remove
}
@Override
public Iterator<T> getLevelOrderIterator() {
return null;
}
@Override
public void setTree(T rootData) {
}
@Override
public void setTree(T rootData, BinaryTreeInterface<T> leftTree,
BinaryTreeInterface<T> rightTree) {
}
}//end BinaryTree

Weitere ähnliche Inhalte

Ähnlich wie Create a class BinarySearchTree- A class that implements the ADT binar.pdf

lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
DIPESH30
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfimport java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
shaktisinhgandhinaga
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
mail931892
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
mail931892
 
I have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdfI have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdf
allystraders
 
C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT III
Minu Rajasekaran
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
Darwin Durand
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
angelsfashion1
 
using the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfusing the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdf
amirthagiftsmadurai
 
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
rambagra74
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
KUNALHARCHANDANI1
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
anukoolelectronics
 
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
public class AVLTreeT extends ComparableT extends BSTT {   p.pdfpublic class AVLTreeT extends ComparableT extends BSTT {   p.pdf
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
agmobiles
 

Ähnlich wie Create a class BinarySearchTree- A class that implements the ADT binar.pdf (20)

lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
 
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdfimport java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
import java.util.Scanner;class BinaryNode{     BinaryNode left.pdf
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
I have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdfI have created a class hasdhedDictionary that implements the Diction.pdf
I have created a class hasdhedDictionary that implements the Diction.pdf
 
C# Application program UNIT III
C# Application program UNIT IIIC# Application program UNIT III
C# Application program UNIT III
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
C# Generics
C# GenericsC# Generics
C# Generics
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 
using the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfusing the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdf
 
Complete the C++ program and implement the routines that are not .docx
  Complete the C++ program and implement the routines that are not .docx  Complete the C++ program and implement the routines that are not .docx
Complete the C++ program and implement the routines that are not .docx
 
Complete the C++ program and implement the routines that are not .docx
  Complete the C++ program and implement the routines that are not .docx  Complete the C++ program and implement the routines that are not .docx
Complete the C++ program and implement the routines that are not .docx
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
public class AVLTreeT extends ComparableT extends BSTT {   p.pdfpublic class AVLTreeT extends ComparableT extends BSTT {   p.pdf
public class AVLTreeT extends ComparableT extends BSTT { p.pdf
 

Mehr von shyamsunder1211

Current C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdfCurrent C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
shyamsunder1211
 
Create this program in visual studio C# The design of the form A text.pdf
Create this program in visual studio C# The design of the form A text.pdfCreate this program in visual studio C# The design of the form A text.pdf
Create this program in visual studio C# The design of the form A text.pdf
shyamsunder1211
 

Mehr von shyamsunder1211 (20)

Cybersecurity in the Cloud - In this two-part discussion post- you wil.pdf
Cybersecurity in the Cloud - In this two-part discussion post- you wil.pdfCybersecurity in the Cloud - In this two-part discussion post- you wil.pdf
Cybersecurity in the Cloud - In this two-part discussion post- you wil.pdf
 
Custom objects in Salesforce can result from what activity- System Adm.pdf
Custom objects in Salesforce can result from what activity- System Adm.pdfCustom objects in Salesforce can result from what activity- System Adm.pdf
Custom objects in Salesforce can result from what activity- System Adm.pdf
 
Currently there are no taxes on the market for good X- At the current.pdf
Currently there are no taxes on the market for good X- At the current.pdfCurrently there are no taxes on the market for good X- At the current.pdf
Currently there are no taxes on the market for good X- At the current.pdf
 
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdfCurrent C++ code- parse-h -- This file contains the function prototype (1).pdf
Current C++ code- parse-h -- This file contains the function prototype (1).pdf
 
Current information for the Healey Company follows- Beginning raw mate.pdf
Current information for the Healey Company follows- Beginning raw mate.pdfCurrent information for the Healey Company follows- Beginning raw mate.pdf
Current information for the Healey Company follows- Beginning raw mate.pdf
 
Current Attempt in Progress Your answer is incorrect- Examples of regu.pdf
Current Attempt in Progress Your answer is incorrect- Examples of regu.pdfCurrent Attempt in Progress Your answer is incorrect- Examples of regu.pdf
Current Attempt in Progress Your answer is incorrect- Examples of regu.pdf
 
Current Attempt in Progress These items are taken from the financial s (1).pdf
Current Attempt in Progress These items are taken from the financial s (1).pdfCurrent Attempt in Progress These items are taken from the financial s (1).pdf
Current Attempt in Progress These items are taken from the financial s (1).pdf
 
Current Attempt in Progress The following information is available for.pdf
Current Attempt in Progress The following information is available for.pdfCurrent Attempt in Progress The following information is available for.pdf
Current Attempt in Progress The following information is available for.pdf
 
Current Attempt in Progress Here is financial information for Sunland.pdf
Current Attempt in Progress Here is financial information for Sunland.pdfCurrent Attempt in Progress Here is financial information for Sunland.pdf
Current Attempt in Progress Here is financial information for Sunland.pdf
 
Current Attempt in Progress Below is a partial listing of the adjusted.pdf
Current Attempt in Progress Below is a partial listing of the adjusted.pdfCurrent Attempt in Progress Below is a partial listing of the adjusted.pdf
Current Attempt in Progress Below is a partial listing of the adjusted.pdf
 
Current assets Current assets - contra Current liabilities Current lia.pdf
Current assets Current assets - contra Current liabilities Current lia.pdfCurrent assets Current assets - contra Current liabilities Current lia.pdf
Current assets Current assets - contra Current liabilities Current lia.pdf
 
Cuck Ai That Appir first noter- fecernd mater mecanil tein- Bret tarie.pdf
Cuck Ai That Appir first noter- fecernd mater mecanil tein- Bret tarie.pdfCuck Ai That Appir first noter- fecernd mater mecanil tein- Bret tarie.pdf
Cuck Ai That Appir first noter- fecernd mater mecanil tein- Bret tarie.pdf
 
Cross-sectional surveys can be characterized as- occurring at two po.pdf
Cross-sectional surveys can be characterized as-   occurring at two po.pdfCross-sectional surveys can be characterized as-   occurring at two po.pdf
Cross-sectional surveys can be characterized as- occurring at two po.pdf
 
Criminal convictions and judgments are two components of your personal.pdf
Criminal convictions and judgments are two components of your personal.pdfCriminal convictions and judgments are two components of your personal.pdf
Criminal convictions and judgments are two components of your personal.pdf
 
creatively and demonstrates his genuine care for their well-being on a.pdf
creatively and demonstrates his genuine care for their well-being on a.pdfcreatively and demonstrates his genuine care for their well-being on a.pdf
creatively and demonstrates his genuine care for their well-being on a.pdf
 
Create C# Console Program The labels that stay are the only cursor tha.pdf
Create C# Console Program The labels that stay are the only cursor tha.pdfCreate C# Console Program The labels that stay are the only cursor tha.pdf
Create C# Console Program The labels that stay are the only cursor tha.pdf
 
Create this program in visual studio C# The design of the form A text.pdf
Create this program in visual studio C# The design of the form A text.pdfCreate this program in visual studio C# The design of the form A text.pdf
Create this program in visual studio C# The design of the form A text.pdf
 
Create me an activity diagram for this scenario- A Call Taker receives.pdf
Create me an activity diagram for this scenario- A Call Taker receives.pdfCreate me an activity diagram for this scenario- A Call Taker receives.pdf
Create me an activity diagram for this scenario- A Call Taker receives.pdf
 
Create some simple Python code which does the following- Creates a tup.pdf
Create some simple Python code which does the following- Creates a tup.pdfCreate some simple Python code which does the following- Creates a tup.pdf
Create some simple Python code which does the following- Creates a tup.pdf
 
Create the Function for the program that will prompt the user to enter.pdf
Create the Function for the program that will prompt the user to enter.pdfCreate the Function for the program that will prompt the user to enter.pdf
Create the Function for the program that will prompt the user to enter.pdf
 

Kürzlich hochgeladen

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
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
heathfieldcps1
 

Kürzlich hochgeladen (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

Create a class BinarySearchTree- A class that implements the ADT binar.pdf

  • 1. Create a class BinarySearchTree. A class that implements the ADT binary search tree by extending BinaryTree. Recursive version. public class BinarySearchTree<T extends Comparable<? super T>> extends BinaryTree<T> implements SearchTreeInterface<T> { public BinarySearchTree () { super(); } // end default constructor public BinarySearchTree (T rootEntry) { super(); setRootNode(new BinaryNode<>(rootEntry)); } // end constructor public void setTree (T rootData) // Disable setTree (see Segment 25.6) { throw new UnsupportedOperationException(); } // end setTree public void setTree (T rootData, BinaryTreeInterface<T> leftTree, BinaryTreeInterface<T> rightTree) { throw new UnsupportedOperationException(); } // end setTree //... public T remove (T entry) { ReturnObject oldEntry = new ReturnObject(null); BinaryNode<T> newRoot = removeEntry(getRootNode(), entry, oldEntry); setRootNode(newRoot); return oldEntry.get(); } // end remove //... private class ReturnObject { private T item; private ReturnObject(T entry)
  • 2. { item = entry; } // end constructor public T get() { return item; } // end get public void set(T entry) { item = entry; } // end set } // end ReturnObject } // end BinarySearchTree HERE IS BinaryTree.java import java.util.Iterator; import java.util.NoSuchElementException; public class BinaryTree<T> implements BinaryTreeInterface<T> { private BinaryNode<T> root; public BinaryTree() { root = null; } public BinaryTree(T rootData) { root = new BinaryNode<>(rootData); } public BinaryTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree) { privateSetTree(rootData, leftTree, rightTree); } private void privateSetTree(T rootData, BinaryTree<T> leftTree, BinaryTree<T> rightTree) { root = new BinaryNode<>(rootData); if (leftTree != null && !leftTree.isEmpty()) { root.setLeftChild(leftTree.root); }
  • 3. if (rightTree != null && !rightTree.isEmpty()) { if (rightTree != leftTree) { root.setRightChild(rightTree.root); } else { root.setRightChild(rightTree.root.copy()); } } if (leftTree != null && leftTree != this) { leftTree.clear(); } if (rightTree != null && rightTree != this) { rightTree.clear(); } } @Override public T getRootData() { if (isEmpty()) { throw new EmptyTreeException("The tree is empty."); } return root.getData(); } @Override public int getHeight() { return root.getHeight(); } @Override public int getNumberOfNodes() { return root.getNumberOfNodes(); } @Override public boolean isEmpty() { return root == null; } @Override public void clear() { root = null; }
  • 4. @Override public Iterator<T> getPreorderIterator() { return new PreorderIterator(); } @Override public Iterator<T> getInorderIterator() { return new InorderIterator(); } @Override public Iterator<T> getPostorderIterator() { return new PostorderIterator(); } private class PreorderIterator implements Iterator<T> { private StackInterface<BinaryNode<T>> nodeStack; public PreorderIterator() { nodeStack = new LinkedStack<>(); if (root != null) { nodeStack.push(root); } } public boolean hasNext() { return !nodeStack.isEmpty(); } public T next() { BinaryNode<T> nextNode; if (hasNext()) { nextNode = nodeStack.pop(); BinaryNode<T> leftChild = nextNode.getLeftChild(); BinaryNode<T> rightChild = nextNode.getRightChild(); if (rightChild != null) { nodeStack.push(rightChild); } if (leftChild != null) { nodeStack.push(leftChild); } } else {
  • 5. throw new NoSuchElementException(); } return nextNode.getData(); } public void remove() { throw new UnsupportedOperationException(); } } private class InorderIterator implements Iterator<T> { private StackInterface<BinaryNode<T>> nodeStack; private BinaryNode<T> currentNode; public InorderIterator() { nodeStack = new LinkedStack<>(); currentNode = root; } public boolean hasNext() { return !nodeStack.isEmpty() || (currentNode != null); } public T next() { BinaryNode<T> nextNode = null; while (currentNode !=null) { nodeStack.push(currentNode); currentNode = currentNode.getLeftChild(); } if (!nodeStack.isEmpty()) { nextNode = nodeStack.pop(); currentNode = nextNode.getRightChild(); } else { throw new NoSuchElementException(); } return nextNode.getData(); } public void remove() { throw new UnsupportedOperationException(); } }
  • 6. private class PostorderIterator implements Iterator<T> { private StackInterface<BinaryNode<T>> nodeStack; private BinaryNode<T> currentNode; private BinaryNode<T> lastNodeVisited; public PostorderIterator() { nodeStack = new LinkedStack<>(); currentNode = root; lastNodeVisited = null; } public boolean hasNext() { return !nodeStack.isEmpty() || (currentNode != null); } public T next() { BinaryNode<T> leftChild, rightChild, nextNode = null; while (currentNode != null) { nodeStack.push(currentNode); leftChild = currentNode.getLeftChild(); if (leftChild == null) { currentNode = currentNode.getRightChild(); } else { currentNode = leftChild; } } // stack is not empty, pop top node if (!nodeStack.isEmpty()) { nextNode = nodeStack.pop(); BinaryNode<T> parent = null; if (!nodeStack.isEmpty()) { parent = nodeStack.peek(); if (nextNode == parent.getLeftChild()) { currentNode = parent.getRightChild(); } else { currentNode = null; } } else { currentNode = null; } } else { throw new NoSuchElementException(); }
  • 7. return nextNode.getData(); } public void remove() { throw new UnsupportedOperationException(); }//end remove } @Override public Iterator<T> getLevelOrderIterator() { return null; } @Override public void setTree(T rootData) { } @Override public void setTree(T rootData, BinaryTreeInterface<T> leftTree, BinaryTreeInterface<T> rightTree) { } }//end BinaryTree