SlideShare a Scribd company logo
Given the following code
package data1;
import java.util.*;
/*public class BST> implementing a set ADT and containing the following:
* private inner class BinaryNode representing a node with a (possibly) left child and a (possibly)
right child
** instance fields BinaryNode root, int size
* contains/insert/remove method - w/ O(height) complexity
** size O(1), isEmpty O(1), clear O(1),
*** findMin, findMax, findHeight methods - w/ O(height) complexity
**** toString() method printing set (in-order traversal) and the tree (BFS traversal)
**
*/
publicclass BST> {
private BinaryNode root;
privateint size;
//Search opertion of Set ADT
publicboolean contains(E value) {
return contains(root, value);
}
//Insert opertion of Set ADT
publicvoid insert(E value) {
root = insert(root, value);
size++;
}
//Remove operation of Set ADT
publicvoid remove(E value){
root = remove(root, value);
size--;
}
publicint size(){
return size;
}
publicboolean isEmpty(){
return root == null;
}
publicvoid clear(){
root = null;
size = 0;
}
public E findMin(){
return findMin(root);
}
public E findMax(){
return findMax(root);
}
publicint findHeight(){
return root.height();
}
public String toString(){
if(root == null)
return "set {} stored in an empty tree.n";
String elements = root.inOrder().toString();
return "set {" + elements.substring(1,elements.length()-1) + "} stored in tree n" + root;
}
private E findMin(BinaryNode node){
if(node == null)
returnnull;
if(node.left == null)
return node.element;
return findMin(node.left);
}
private E findMax(BinaryNode node){
if(node == null)
returnnull;
if(node.right == null)
return node.element;
return findMax(node.right);
}
privateboolean contains(BinaryNode node, E value) {
if (node == null)//node represents an empty substree
returnfalse;
int comparisonResult = value.compareTo(node.element);
if(comparisonResult < 0)//if value is less than root's value
return contains(node.left, value);
if(comparisonResult > 0)//if value is greater than root's value
return contains(node.right, value);
returntrue;//successful search
}
private BinaryNode insert(BinaryNode node, E value) {
if (node == null)//base case: empty tree
returnnew BinaryNode<>(value);
if (value.compareTo(node.element) < 0)
node.left = insert(node.left, value);//insert recursively to left-subtree
elseif (value.compareTo(node.element) > 0)
node.right = insert(node.right, value);//insert recursively to right-subtree
else {//duplicate value cannot be inserted in a BST implementing the Set ADT
size--;//insertion failed!
//System.out.print("BST.insert: Warning: " + value + " is already stored in the tree n" + node);
}
return node;
}
private BinaryNode remove(BinaryNode node, E value) {
if (node == null) {//base case: empty tree
System.out.println("BST.remove: Warning: " + value + " doesn't exist in the tree.");
size++;//removal failed!
return node;
}
if (value.compareTo(node.element) < 0)
node.left = remove(node.left, value);
elseif (value.compareTo(node.element) > 0)
node.right = remove(node.right, value);
else {//we have found the node that needs to be removed!
if (node.left != null && node.right != null) {//remove a node with two children
node.element = findMin(node.right);//replace it by the leftmost node at right subtree
node.right = remove(node.right, node.element);//then, remove the leftmost node in the right
subtree
/*alternative:
node.element = findMax(node.left);//replace it by the rightmost node at left subtree
node.left = remove(node.left, node.element);//then, remove the rightmost node in the left subtree
*/
} elseif (node.left != null)//remove a node with a left child only
return node.left;
elseif (node.right != null)//remove a node with a right child only
return node.right;
else//remove a node with no child!
returnnull;
}
return node;
}
privateclass BinaryNode {
public E element;//data
public BinaryNode left;//left child
public BinaryNode right;//right child
//constructor for leaves
public BinaryNode(E element) {
this(element, null, null);
}
//constructor for internal nodes
public BinaryNode(E element, BinaryNode left, BinaryNode right) {
this.left = left;
this.right = right;
this.element = element;
}
publicint height() {
if (left == null && right == null)
return 0;
if (left == null)
return 1 + right.height();
if (right == null)
return 1 + left.height();
return 1 + Math.max(left.height(), right.height());
}
publicint size() {
int size = 1;//counting root
if (left != null)//counting left subtree nodes
size += left.size();
if (right != null)//counting right subtree nodes
size += right.size();
return size;
}
publicvoid printPreOrder() {
System.out.print(element + " ");
if (left != null)
left.printPreOrder();
if (right != null)
right.printPreOrder();
}
publicvoid printPostOrder() {
if (left != null)
left.printPostOrder();
if (right != null)
right.printPostOrder();
System.out.print(element + " ");
}
publicvoid printInOrder() {
if (left != null)
left.printInOrder();
System.out.print(element + " ");
if (right != null)
right.printInOrder();
}
public ArrayList inOrder(){
ArrayList list = new ArrayList<>();
Stack stack = new Stack<>();
stack.push(this);
while(!stack.empty()){
Object cur = stack.pop();
if(cur instanceof BinaryNode) {
BinaryNode node = (BinaryNode) cur;
if (node.right != null)
stack.push(node.right);
stack.push(node.element);
if (node.left != null)
stack.push(node.left);
}else
list.add((E)cur);
}
return list;
}
publicvoid printBFS() {
Queue q = new LinkedList<>();
q.add(this);
while (!q.isEmpty()) {
BinaryNode cur = q.remove();
System.out.print(cur.element + " ");
if (cur.left != null)
q.add(cur.left);
if (cur.right != null)
q.add(cur.right);
}
}
publicvoid printDFS() {
Stack stack = new Stack<>();
stack.add(this);
while (!stack.empty()) {
BinaryNode cur = stack.pop();
System.out.print(cur.element + " ");
if (cur.right != null)
stack.push(cur.right);
if (cur.left != null)
stack.push(cur.left);
}
}
@Override
public String toString() {
if (left == null && right == null && element == null)
return "";
Queue list = new LinkedList<>();
String result = "";
list.add(this);
list.add(null);
int level = (int) Math.pow(2, height());
BinaryNode dummy = new BinaryNode(null);
while (!list.isEmpty()) {
boolean allDummies = true;
for (BinaryNode b : list)
if (b != dummy && b != null) {
allDummies = false;
break;
}
BinaryNode cur = list.remove();
if (cur == null || allDummies)
break;
for (int i = 0; i < level - 1; i++)
result += 't';
if (cur != dummy)
result += cur.element;
for (int i = 0; i < level + 1; i++)
result += 't';
if (cur.left != null)
list.add(cur.left);
else
list.add(dummy);
if (cur.right != null)
list.add(cur.right);
else
list.add(dummy);
if (list.peek() == null) {
for (int i = 0; i < height(); i++)
result += 'n';
list.remove();
list.add(null);
level /= 2;
}
}
return result + "n";
}
}
Q:
Write a Java method with the following signature that receives the post-order traversal of a
binary search tree (BST) in the form of an array of integers and constructs the BST. For example,
if the array is [4, 5, 6], the tree looks like this(notice the structure of it):
6
5
4
but, if the array is [4, 6, 5], the tree looks like this:
5
4 6
and if the array is [5, 4, 6], the tree looks like this:
6
4
5
public static BST constructFromPostOrder(int[] postorder){...}
Q:
Write a Java method with the following signature that receives the post-order traversal of a
binary search tree (BST) in the form of an array of integers and constructs the BST. For example,
if the array is [4, 5, 6], the tree looks like this(notice the structure of it):
6
5
4
but, if the array is [4, 6, 5], the tree looks like this:
5
4 6
and if the array is [5, 4, 6], the tree looks like this:
6
4
5
public static BST constructFromPostOrder(int[] postorder){...}

More Related Content

Similar to Given the following codepackage data1;import java.util.;p.pdf

import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdf
ADITIEYEWEAR
 
Here is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfHere is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdf
manjan6
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdf
allystraders
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
arrowmobile
 
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
rock73
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
connellalykshamesb60
 
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
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
Pranav Ghildiyal
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
ssuser0be977
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Footageetoffe16
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docx
ajoy21
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
Rahul Chugh
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
ajoy21
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
archiesgallery
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
Lakshmi Sarvani Videla
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 

Similar to Given the following codepackage data1;import java.util.;p.pdf (20)

import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdf
 
Here is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdfHere is the code given in the instructionsclass AVL {.pdf
Here is the code given in the instructionsclass AVL {.pdf
 
I have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdfI have a .java program that I need to modify so that it1) reads i.pdf
I have a .java program that I need to modify so that it1) reads i.pdf
 
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdfHere is the editable codeSolutionimport java.util.NoSuchEleme.pdf
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
 
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
 
Using the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdfUsing the provided table interface table.h and the sample linked lis.pdf
Using the provided table interface table.h and the sample linked lis.pdf
 
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
 
CBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical fileCBSE Class XII Comp sc practical file
CBSE Class XII Comp sc practical file
 
dynamicList.ppt
dynamicList.pptdynamicList.ppt
dynamicList.ppt
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docx
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdfModify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
Need Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdfNeed Help with this Java Assignment. Program should be done in JAVA .pdf
Need Help with this Java Assignment. Program should be done in JAVA .pdf
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdf
 

More from illyasraja7

I really need help with this assignment it is multiple parts# Part.pdf
I really need help with this assignment it is multiple parts# Part.pdfI really need help with this assignment it is multiple parts# Part.pdf
I really need help with this assignment it is multiple parts# Part.pdf
illyasraja7
 
I need help figuring out how to add something that make sure user en.pdf
I need help figuring out how to add something that make sure user en.pdfI need help figuring out how to add something that make sure user en.pdf
I need help figuring out how to add something that make sure user en.pdf
illyasraja7
 
how would I write out this getRentalsByCityAndProvince function to s.pdf
how would I write out this getRentalsByCityAndProvince function to s.pdfhow would I write out this getRentalsByCityAndProvince function to s.pdf
how would I write out this getRentalsByCityAndProvince function to s.pdf
illyasraja7
 
How much is too much transparency How much is too little Look for .pdf
How much is too much transparency How much is too little Look for .pdfHow much is too much transparency How much is too little Look for .pdf
How much is too much transparency How much is too little Look for .pdf
illyasraja7
 
hi i need help with this Database AssignmentOverviewHere are req.pdf
hi i need help with this Database AssignmentOverviewHere are req.pdfhi i need help with this Database AssignmentOverviewHere are req.pdf
hi i need help with this Database AssignmentOverviewHere are req.pdf
illyasraja7
 
Hamilton is a member in public practice since 2005. She is a sole pr.pdf
Hamilton is a member in public practice since 2005. She is a sole pr.pdfHamilton is a member in public practice since 2005. She is a sole pr.pdf
Hamilton is a member in public practice since 2005. She is a sole pr.pdf
illyasraja7
 
Given main(), complete the SongNode class to include the printSong.pdf
Given main(), complete the SongNode class to include the printSong.pdfGiven main(), complete the SongNode class to include the printSong.pdf
Given main(), complete the SongNode class to include the printSong.pdf
illyasraja7
 
Given main() in the Inventory class, define an insertAtFront() metho.pdf
Given main() in the Inventory class, define an insertAtFront() metho.pdfGiven main() in the Inventory class, define an insertAtFront() metho.pdf
Given main() in the Inventory class, define an insertAtFront() metho.pdf
illyasraja7
 
Give a background of First National Bank (FNB) This should include.pdf
Give a background of First National Bank (FNB) This should include.pdfGive a background of First National Bank (FNB) This should include.pdf
Give a background of First National Bank (FNB) This should include.pdf
illyasraja7
 
For your third competency project, the policy position presentation,.pdf
For your third competency project, the policy position presentation,.pdfFor your third competency project, the policy position presentation,.pdf
For your third competency project, the policy position presentation,.pdf
illyasraja7
 
FROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdf
FROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdfFROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdf
FROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdf
illyasraja7
 
HelloIn Operating systems, under critical sectionEach process h.pdf
HelloIn Operating systems, under critical sectionEach process h.pdfHelloIn Operating systems, under critical sectionEach process h.pdf
HelloIn Operating systems, under critical sectionEach process h.pdf
illyasraja7
 
Find a current news article or video (within the past 12 months) tha.pdf
Find a current news article or video (within the past 12 months) tha.pdfFind a current news article or video (within the past 12 months) tha.pdf
Find a current news article or video (within the past 12 months) tha.pdf
illyasraja7
 
Forecasters use different forecasting techniques to determine the va.pdf
Forecasters use different forecasting techniques to determine the va.pdfForecasters use different forecasting techniques to determine the va.pdf
Forecasters use different forecasting techniques to determine the va.pdf
illyasraja7
 
Fact Scenario You act for a client in an acrimonious litigation file.pdf
Fact Scenario You act for a client in an acrimonious litigation file.pdfFact Scenario You act for a client in an acrimonious litigation file.pdf
Fact Scenario You act for a client in an acrimonious litigation file.pdf
illyasraja7
 

More from illyasraja7 (15)

I really need help with this assignment it is multiple parts# Part.pdf
I really need help with this assignment it is multiple parts# Part.pdfI really need help with this assignment it is multiple parts# Part.pdf
I really need help with this assignment it is multiple parts# Part.pdf
 
I need help figuring out how to add something that make sure user en.pdf
I need help figuring out how to add something that make sure user en.pdfI need help figuring out how to add something that make sure user en.pdf
I need help figuring out how to add something that make sure user en.pdf
 
how would I write out this getRentalsByCityAndProvince function to s.pdf
how would I write out this getRentalsByCityAndProvince function to s.pdfhow would I write out this getRentalsByCityAndProvince function to s.pdf
how would I write out this getRentalsByCityAndProvince function to s.pdf
 
How much is too much transparency How much is too little Look for .pdf
How much is too much transparency How much is too little Look for .pdfHow much is too much transparency How much is too little Look for .pdf
How much is too much transparency How much is too little Look for .pdf
 
hi i need help with this Database AssignmentOverviewHere are req.pdf
hi i need help with this Database AssignmentOverviewHere are req.pdfhi i need help with this Database AssignmentOverviewHere are req.pdf
hi i need help with this Database AssignmentOverviewHere are req.pdf
 
Hamilton is a member in public practice since 2005. She is a sole pr.pdf
Hamilton is a member in public practice since 2005. She is a sole pr.pdfHamilton is a member in public practice since 2005. She is a sole pr.pdf
Hamilton is a member in public practice since 2005. She is a sole pr.pdf
 
Given main(), complete the SongNode class to include the printSong.pdf
Given main(), complete the SongNode class to include the printSong.pdfGiven main(), complete the SongNode class to include the printSong.pdf
Given main(), complete the SongNode class to include the printSong.pdf
 
Given main() in the Inventory class, define an insertAtFront() metho.pdf
Given main() in the Inventory class, define an insertAtFront() metho.pdfGiven main() in the Inventory class, define an insertAtFront() metho.pdf
Given main() in the Inventory class, define an insertAtFront() metho.pdf
 
Give a background of First National Bank (FNB) This should include.pdf
Give a background of First National Bank (FNB) This should include.pdfGive a background of First National Bank (FNB) This should include.pdf
Give a background of First National Bank (FNB) This should include.pdf
 
For your third competency project, the policy position presentation,.pdf
For your third competency project, the policy position presentation,.pdfFor your third competency project, the policy position presentation,.pdf
For your third competency project, the policy position presentation,.pdf
 
FROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdf
FROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdfFROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdf
FROM The Starry Messenger ASTRONOMICAL MESSAGEWhich contains and.pdf
 
HelloIn Operating systems, under critical sectionEach process h.pdf
HelloIn Operating systems, under critical sectionEach process h.pdfHelloIn Operating systems, under critical sectionEach process h.pdf
HelloIn Operating systems, under critical sectionEach process h.pdf
 
Find a current news article or video (within the past 12 months) tha.pdf
Find a current news article or video (within the past 12 months) tha.pdfFind a current news article or video (within the past 12 months) tha.pdf
Find a current news article or video (within the past 12 months) tha.pdf
 
Forecasters use different forecasting techniques to determine the va.pdf
Forecasters use different forecasting techniques to determine the va.pdfForecasters use different forecasting techniques to determine the va.pdf
Forecasters use different forecasting techniques to determine the va.pdf
 
Fact Scenario You act for a client in an acrimonious litigation file.pdf
Fact Scenario You act for a client in an acrimonious litigation file.pdfFact Scenario You act for a client in an acrimonious litigation file.pdf
Fact Scenario You act for a client in an acrimonious litigation file.pdf
 

Recently uploaded

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 

Recently uploaded (20)

Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 

Given the following codepackage data1;import java.util.;p.pdf

  • 1. Given the following code package data1; import java.util.*; /*public class BST> implementing a set ADT and containing the following: * private inner class BinaryNode representing a node with a (possibly) left child and a (possibly) right child ** instance fields BinaryNode root, int size * contains/insert/remove method - w/ O(height) complexity ** size O(1), isEmpty O(1), clear O(1), *** findMin, findMax, findHeight methods - w/ O(height) complexity **** toString() method printing set (in-order traversal) and the tree (BFS traversal) ** */ publicclass BST> { private BinaryNode root; privateint size; //Search opertion of Set ADT publicboolean contains(E value) { return contains(root, value); } //Insert opertion of Set ADT publicvoid insert(E value) { root = insert(root, value); size++; } //Remove operation of Set ADT publicvoid remove(E value){ root = remove(root, value); size--; } publicint size(){ return size; } publicboolean isEmpty(){
  • 2. return root == null; } publicvoid clear(){ root = null; size = 0; } public E findMin(){ return findMin(root); } public E findMax(){ return findMax(root); } publicint findHeight(){ return root.height(); } public String toString(){ if(root == null) return "set {} stored in an empty tree.n"; String elements = root.inOrder().toString(); return "set {" + elements.substring(1,elements.length()-1) + "} stored in tree n" + root; } private E findMin(BinaryNode node){ if(node == null) returnnull; if(node.left == null) return node.element; return findMin(node.left); } private E findMax(BinaryNode node){ if(node == null) returnnull; if(node.right == null) return node.element; return findMax(node.right); } privateboolean contains(BinaryNode node, E value) {
  • 3. if (node == null)//node represents an empty substree returnfalse; int comparisonResult = value.compareTo(node.element); if(comparisonResult < 0)//if value is less than root's value return contains(node.left, value); if(comparisonResult > 0)//if value is greater than root's value return contains(node.right, value); returntrue;//successful search } private BinaryNode insert(BinaryNode node, E value) { if (node == null)//base case: empty tree returnnew BinaryNode<>(value); if (value.compareTo(node.element) < 0) node.left = insert(node.left, value);//insert recursively to left-subtree elseif (value.compareTo(node.element) > 0) node.right = insert(node.right, value);//insert recursively to right-subtree else {//duplicate value cannot be inserted in a BST implementing the Set ADT size--;//insertion failed! //System.out.print("BST.insert: Warning: " + value + " is already stored in the tree n" + node); } return node; } private BinaryNode remove(BinaryNode node, E value) { if (node == null) {//base case: empty tree System.out.println("BST.remove: Warning: " + value + " doesn't exist in the tree."); size++;//removal failed! return node; } if (value.compareTo(node.element) < 0) node.left = remove(node.left, value); elseif (value.compareTo(node.element) > 0) node.right = remove(node.right, value); else {//we have found the node that needs to be removed! if (node.left != null && node.right != null) {//remove a node with two children node.element = findMin(node.right);//replace it by the leftmost node at right subtree node.right = remove(node.right, node.element);//then, remove the leftmost node in the right
  • 4. subtree /*alternative: node.element = findMax(node.left);//replace it by the rightmost node at left subtree node.left = remove(node.left, node.element);//then, remove the rightmost node in the left subtree */ } elseif (node.left != null)//remove a node with a left child only return node.left; elseif (node.right != null)//remove a node with a right child only return node.right; else//remove a node with no child! returnnull; } return node; } privateclass BinaryNode { public E element;//data public BinaryNode left;//left child public BinaryNode right;//right child //constructor for leaves public BinaryNode(E element) { this(element, null, null); } //constructor for internal nodes public BinaryNode(E element, BinaryNode left, BinaryNode right) { this.left = left; this.right = right; this.element = element; } publicint height() { if (left == null && right == null) return 0; if (left == null) return 1 + right.height(); if (right == null) return 1 + left.height();
  • 5. return 1 + Math.max(left.height(), right.height()); } publicint size() { int size = 1;//counting root if (left != null)//counting left subtree nodes size += left.size(); if (right != null)//counting right subtree nodes size += right.size(); return size; } publicvoid printPreOrder() { System.out.print(element + " "); if (left != null) left.printPreOrder(); if (right != null) right.printPreOrder(); } publicvoid printPostOrder() { if (left != null) left.printPostOrder(); if (right != null) right.printPostOrder(); System.out.print(element + " "); } publicvoid printInOrder() { if (left != null) left.printInOrder(); System.out.print(element + " "); if (right != null) right.printInOrder(); } public ArrayList inOrder(){ ArrayList list = new ArrayList<>(); Stack stack = new Stack<>(); stack.push(this);
  • 6. while(!stack.empty()){ Object cur = stack.pop(); if(cur instanceof BinaryNode) { BinaryNode node = (BinaryNode) cur; if (node.right != null) stack.push(node.right); stack.push(node.element); if (node.left != null) stack.push(node.left); }else list.add((E)cur); } return list; } publicvoid printBFS() { Queue q = new LinkedList<>(); q.add(this); while (!q.isEmpty()) { BinaryNode cur = q.remove(); System.out.print(cur.element + " "); if (cur.left != null) q.add(cur.left); if (cur.right != null) q.add(cur.right); } } publicvoid printDFS() { Stack stack = new Stack<>(); stack.add(this); while (!stack.empty()) { BinaryNode cur = stack.pop();
  • 7. System.out.print(cur.element + " "); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); } } @Override public String toString() { if (left == null && right == null && element == null) return ""; Queue list = new LinkedList<>(); String result = ""; list.add(this); list.add(null); int level = (int) Math.pow(2, height()); BinaryNode dummy = new BinaryNode(null); while (!list.isEmpty()) { boolean allDummies = true; for (BinaryNode b : list) if (b != dummy && b != null) { allDummies = false; break; } BinaryNode cur = list.remove(); if (cur == null || allDummies) break; for (int i = 0; i < level - 1; i++)
  • 8. result += 't'; if (cur != dummy) result += cur.element; for (int i = 0; i < level + 1; i++) result += 't'; if (cur.left != null) list.add(cur.left); else list.add(dummy); if (cur.right != null) list.add(cur.right); else list.add(dummy); if (list.peek() == null) { for (int i = 0; i < height(); i++) result += 'n'; list.remove(); list.add(null); level /= 2; } } return result + "n"; } } Q: Write a Java method with the following signature that receives the post-order traversal of a binary search tree (BST) in the form of an array of integers and constructs the BST. For example, if the array is [4, 5, 6], the tree looks like this(notice the structure of it): 6 5 4 but, if the array is [4, 6, 5], the tree looks like this:
  • 9. 5 4 6 and if the array is [5, 4, 6], the tree looks like this: 6 4 5 public static BST constructFromPostOrder(int[] postorder){...} Q: Write a Java method with the following signature that receives the post-order traversal of a binary search tree (BST) in the form of an array of integers and constructs the BST. For example, if the array is [4, 5, 6], the tree looks like this(notice the structure of it): 6 5 4 but, if the array is [4, 6, 5], the tree looks like this: 5 4 6 and if the array is [5, 4, 6], the tree looks like this: 6 4 5 public static BST constructFromPostOrder(int[] postorder){...}