SlideShare a Scribd company logo
1 of 9
Download to read offline
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 Construct BST from postorder traversal

import javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfimport javautilQueue import javautilLinkedList import .pdf
import javautilQueue import javautilLinkedList import .pdfADITIEYEWEAR
 
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 {.pdfmanjan6
 
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.pdfallystraders
 
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.pdfarrowmobile
 
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
 
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.pdfconnellalykshamesb60
 
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.pdfshaktisinhgandhinaga
 
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 filePranav Ghildiyal
 
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 .pdfFootageetoffe16
 
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.docxajoy21
 
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.pdfarjuncorner565
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
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.docxajoy21
 
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 .pdfarchiesgallery
 
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 .docxdebishakespeare
 
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 structuresLakshmi 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-------------.pdfshanki7
 
(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
 

Similar to Construct BST from postorder traversal (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
 
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
 
(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
 

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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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 .pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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,.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 
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.pdfillyasraja7
 

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

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
 
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
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

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...
 
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
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
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🔝
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
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
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
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
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Construct BST from postorder traversal

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