SlideShare a Scribd company logo
(1)Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. I of
BST have the same data from each input record.
Download traversal-lab.pptx, inventory.txt, BinNode.java, BSTNode.java, BST.java,
Dictionary.java .
Perform specifications as follow:
(a)Provide Add, Delete and Retrieve functions for user to access the database. Reject duplicate
record when add a new record.
(b)Modify BST.java to add printpostOrder, printpreOrder methods.
(c)At the end, display inorder, postorder and preorder of the tree.
Codes:
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** ADT for binary tree nodes */
public interface BinNode {
/** Get and set the element value */
public E element();
public void setElement(E v);
/** @return The left child */
public BinNode left();
/** @return The right child */
public BinNode right();
/** @return True if a leaf node, false otherwise */
public boolean isLeaf();
}
//********************************************************************
// StringTree.java
//
//********************************************************************
import java.util.*;
public class StringTree
{
private Node root;
//----------------------------------------------------------------
// Creates an initially empty tree.
//----------------------------------------------------------------
public StringTree()
{
root = null;
}
//----------------------------------------------------------------
// Adds a string to the tree.
//----------------------------------------------------------------
public void addString (String str)
{
root = addStringToSubTree(str, root);
}
//----------------------------------------------------------------
// Adds a string to the subtree with the given root node
//----------------------------------------------------------------
private Node addStringToSubTree (String str, Node node)
{
Node result = node;
if (node == null)
result = new Node(str);
// If the new string comes before the string in the node, add
// the new string to the left child. Otherwise, add it to the
// right child.
else
if (str.compareTo(node.value) < 0)
node.left = addStringToSubTree(str, node.left);
else
node.right = addStringToSubTree(str, node.right);
return result;
}
//----------------------------------------------------------------
// Prints the result of a depth-first traversal of the tree using
// recursion.
//----------------------------------------------------------------
public void traverseWithRecursion()
{
traverseWithRecursion(root);
}
//----------------------------------------------------------------
// Prints the elements in the specified tree using recursion.
//----------------------------------------------------------------
private void traverseWithRecursion (Node node)
{
if (node != null)
{
traverseWithRecursion (node.left);
System.out.print (node.value+" ");
traverseWithRecursion (node.right);
}
}
}
//********************************************************************
// Node for a binary tree of Strings.
//********************************************************************
class Node
{
public String value;
public Node left;
public Node right;
public Node (String value)
{
this.value = value;
this.left = left;
this.right = right;
}
}
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** Binary tree node implementation: Pointers to children
@param E The data element
@param Key The associated key for the record */
import java.util.*;
class BSTNode implements BinNode {
private Key key; // Key for this node
private E element; // Element for this node
private BSTNode left; // Pointer to left child
private BSTNode right; // Pointer to right child
/** Constructors */
public BSTNode() {left = right = null; }
public BSTNode(Key k, E val)
{ left = right = null; key = k; element = val; }
public BSTNode(Key k, E val,
BSTNode l, BSTNode r)
{ left = l; right = r; key = k; element = val; }
/** Get and set the key value */
public Key key() { return key; }
public void setKey(Key k) { key = k; }
/** Get and set the element value */
public E element() { return element; }
public void setElement(E v) { element = v; }
/** Get and set the left child */
public BSTNode left() { return left; }
public void setLeft(BSTNode p) { left = p; }
/** Get and set the right child */
public BSTNode right() { return right; }
public void setRight(BSTNode p) { right = p; }
/** @return True if a leaf node, false otherwise */
public boolean isLeaf()
{ return (left == null) && (right == null); }
}
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
import java.lang.Comparable;
/** Binary Search Tree implementation for Dictionary ADT */
class BST, E>
implements Dictionary {
private BSTNode root; // Root of the BST
int nodecount; // Number of nodes in the BST
/** Constructor */
BST() { root = null; nodecount = 0; }
/** Reinitialize tree */
public void clear() { root = null; nodecount = 0; }
/** Insert a record into the tree.
@param k Key value of the record.
@param e The record to insert. */
public void insert(Key k, E e) {
root = inserthelp(root, k, e);
nodecount++;
}
// Return root
public BSTNode getRoot()
{
return root;
}
/** Remove a record from the tree.
@param k Key value of record to remove.
@return The record removed, null if there is none. */
public E remove(Key k) {
E temp = findhelp(root, k); // First find it
if (temp != null) {
root = removehelp(root, k); // Now remove it
nodecount--;
}
return temp;
}
/** Remove and return the root node from the dictionary.
@return The record removed, null if tree is empty. */
public E removeAny() {
if (root == null) return null;
E temp = root.element();
root = removehelp(root, root.key());
nodecount--;
return temp;
}
/** @return Record with key value k, null if none exist.
@param k The key value to find. */
public E find(Key k) { return findhelp(root, k); }
/** @return The number of records in the dictionary. */
public int size() { return nodecount; }
private E findhelp(BSTNode rt, Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
return findhelp(rt.left(), k);
else if (rt.key().compareTo(k) == 0) return rt.element();
else return findhelp(rt.right(), k);
}
/** @return The current subtree, modified to contain
the new item */
private BSTNode inserthelp(BSTNode rt,
Key k, E e) {
if (rt == null) return new BSTNode(k, e);
if (rt.key().compareTo(k) > 0)
rt.setLeft(inserthelp(rt.left(), k, e));
else
rt.setRight(inserthelp(rt.right(), k, e));
return rt;
}
/** Remove a node with key value k
@return The tree with the node removed */
private BSTNode removehelp(BSTNode rt,Key k) {
if (rt == null) return null;
if (rt.key().compareTo(k) > 0)
rt.setLeft(removehelp(rt.left(), k));
else if (rt.key().compareTo(k) < 0)
rt.setRight(removehelp(rt.right(), k));
else { // Found it
if (rt.left() == null) return rt.right();
else if (rt.right() == null) return rt.left();
else { // Two children
BSTNode temp = getmin(rt.right());
rt.setElement(temp.element());
rt.setKey(temp.key());
rt.setRight(deletemin(rt.right()));
}
}
return rt;
}
private BSTNode getmin(BSTNode rt) {
if (rt.left() == null) return rt;
return getmin(rt.left());
}
private BSTNode deletemin(BSTNode rt) {
if (rt.left() == null) return rt.right();
rt.setLeft(deletemin(rt.left()));
return rt;
}
private void printhelp(BSTNode rt) {
if (rt == null) return;
printhelp(rt.left());
printVisit(rt.element());
printhelp(rt.right());
}
private StringBuffer out;
public String toString() {
out = new StringBuffer(400);
printhelp(root);
return out.toString();
}
private void printVisit(E it) {
out.append(it + " ");
}
}
/** Source code example for "A Practical Introduction to Data
Structures and Algorithm Analysis, 3rd Edition (Java)"
by Clifford A. Shaffer
Copyright 2008-2011 by Clifford A. Shaffer
*/
/** The Dictionary abstract class. */
public interface Dictionary {
/** Reinitialize dictionary */
public void clear();
/** Insert a record
@param k The key for the record being inserted.
@param e The record being inserted. */
public void insert(Key k, E e);
/** Remove and return a record.
@param k The key of the record to be removed.
@return A maching record. If multiple records match
"k", remove an arbitrary one. Return null if no record
with key "k" exists. */
public E remove(Key k);
/** Remove and return an arbitrary record from dictionary.
@return the record removed, or null if none exists. */
public E removeAny();
/** @return A record matching "k" (null if none exists).
If multiple records match, return an arbitrary one.
@param k The key of the record to find */
public E find(Key k);
/** @return The number of records in the dictionary. */
public int size();
};
Text file :
CT16C1288B
DT14B1225F
MI15B1250A
MI15B1251A
HO03N1095A
HY07D1095BQ
KI04D2593C
DG12A1240AQ
HY03G2593BQ
TO30A1310A
HO03N1095AQ
HO01H1351C
HO01H1350C
FT18A1288B
LR15A1000A
BM12E1000A
VW02B3113A
NI23H1230AQ
LX03D2503A
LX03D2502A
LX03D2502A
VW22A3113B
VW22B3113A
Solution
import java.util.Scanner;
/* Class BSTNode */
class BSTNode
{
BSTNode left, right;
int data;
/* Constructor */
public BSTNode()
{
left = null;
right = null;
data = 0;
}
/* Constructor */
public BSTNode(int n)
{
left = null;
right = null;
data = n;
}
/* Function to set left node */
public void setLeft(BSTNode n)
{
left = n;
}
/* Function to set right node */
public void setRight(BSTNode n)
{
right = n;
}
/* Function to get left node */
public BSTNode getLeft()
{
return left;
}
/* Function to get right node */
public BSTNode getRight()
{
return right;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Class BST */
class BST
{
private BSTNode root;
/* Constructor */
public BST()
{
root = null;
}
/* Function to check if tree is empty */
public boolean isEmpty()
{
return root == null;
}
/* Functions to insert data */
public void insert(int data)
{
root = insert(root, data);
}
/* Function to insert data recursively */
private BSTNode insert(BSTNode node, int data)
{
if (node == null)
node = new BSTNode(data);
else
{
if (data <= node.getData())
node.left = insert(node.left, data);
else
node.right = insert(node.right, data);
}
return node;
}
/* Functions to delete data */
public void delete(int k)
{
if (isEmpty())
System.out.println("Tree Empty");
else if (search(k) == false)
System.out.println("Sorry "+ k +" is not present");
else
{
root = delete(root, k);
System.out.println(k+ " deleted from the tree");
}
}
private BSTNode delete(BSTNode root, int k)
{
BSTNode p, p2, n;
if (root.getData() == k)
{
BSTNode lt, rt;
lt = root.getLeft();
rt = root.getRight();
if (lt == null && rt == null)
return null;
else if (lt == null)
{
p = rt;
return p;
}
else if (rt == null)
{
p = lt;
return p;
}
else
{
p2 = rt;
p = rt;
while (p.getLeft() != null)
p = p.getLeft();
p.setLeft(lt);
return p2;
}
}
if (k < root.getData())
{
n = delete(root.getLeft(), k);
root.setLeft(n);
}
else
{
n = delete(root.getRight(), k);
root.setRight(n);
}
return root;
}
/* Functions to count number of nodes */
public int countNodes()
{
return countNodes(root);
}
/* Function to count number of nodes recursively */
private int countNodes(BSTNode r)
{
if (r == null)
return 0;
else
{
int l = 1;
l += countNodes(r.getLeft());
l += countNodes(r.getRight());
return l;
}
}
/* Functions to search for an element */
public boolean search(int val)
{
return search(root, val);
}
/* Function to search for an element recursively */
private boolean search(BSTNode r, int val)
{
boolean found = false;
while ((r != null) && !found)
{
int rval = r.getData();
if (val < rval)
r = r.getLeft();
else if (val > rval)
r = r.getRight();
else
{
found = true;
break;
}
found = search(r, val);
}
return found;
}
/* Function for inorder traversal */
public void inorder()
{
inorder(root);
}
private void inorder(BSTNode r)
{
if (r != null)
{
inorder(r.getLeft());
System.out.print(r.getData() +" ");
inorder(r.getRight());
}
}
/* Function for preorder traversal */
public void preorder()
{
preorder(root);
}
private void preorder(BSTNode r)
{
if (r != null)
{
System.out.print(r.getData() +" ");
preorder(r.getLeft());
preorder(r.getRight());
}
}
/* Function for postorder traversal */
public void postorder()
{
postorder(root);
}
private void postorder(BSTNode r)
{
if (r != null)
{
postorder(r.getLeft());
postorder(r.getRight());
System.out.print(r.getData() +" ");
}
}
}
/* Class BinarySearchTree */
public class BinarySearchTree
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of BST */
BST bst = new BST();
System.out.println("Binary Search Tree Test ");
char ch;
/* Perform tree operations */
do
{
System.out.println(" Binary Search Tree Operations ");
System.out.println("1. insert ");
System.out.println("2. delete");
System.out.println("3. search");
System.out.println("4. count nodes");
System.out.println("5. check empty");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
bst.insert( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to delete");
bst.delete( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to search");
System.out.println("Search result : "+ bst.search( scan.nextInt() ));
break;
case 4 :
System.out.println("Nodes = "+ bst.countNodes());
break;
case 5 :
System.out.println("Empty status = "+ bst.isEmpty());
break;
default :
System.out.println("Wrong Entry  ");
break;
}
/* Display tree */
System.out.print(" Post order : ");
bst.postorder();
System.out.print(" Pre order : ");
bst.preorder();
System.out.print(" In order : ");
bst.inorder();
System.out.println(" Do you want to continue (Type y or n)  ");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

More Related Content

Similar to (1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf (20)

PDF
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
PDF
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
PPTX
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
DOCX
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
PDF
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
PDF
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 
PDF
StackInterface An interface for the ADT stack. Do not modif.pdf
ARCHANASTOREKOTA
 
PDF
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
anukoolelectronics
 
DOCX
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
rock73
 
PDF
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
PDF
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
PDF
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
rohit219406
 
PPTX
C Assignment Help
Programming Homework Help
 
DOCX
Write a program that displays an AVL tree along with its balance fac.docx
ajoy21
 
KEY
SQLite Techniques
Ben Scheirman
 
ODP
Groovy Ast Transformations (greach)
HamletDRC
 
PPT
Inheritance compiler support
Syed Zaid Irshad
 
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
PDF
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
PDF
Javascript
Vlad Ifrim
 
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 
StackInterface An interface for the ADT stack. Do not modif.pdf
ARCHANASTOREKOTA
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
anukoolelectronics
 
AvlTree.h#ifndef AVL_TREE_H#define AVL_TREE_H#include d.docx
rock73
 
Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf
arjuncorner565
 
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
rohit219406
 
C Assignment Help
Programming Homework Help
 
Write a program that displays an AVL tree along with its balance fac.docx
ajoy21
 
SQLite Techniques
Ben Scheirman
 
Groovy Ast Transformations (greach)
HamletDRC
 
Inheritance compiler support
Syed Zaid Irshad
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
Javascript
Vlad Ifrim
 

More from arihantmobileselepun (20)

PDF
How are the epimysium and tendons relatedA. The epimysium surroun.pdf
arihantmobileselepun
 
PDF
How does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdf
arihantmobileselepun
 
PDF
Gerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdf
arihantmobileselepun
 
PDF
For Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdf
arihantmobileselepun
 
PDF
Find and provide a link to a multi-year capital plan from any Illino.pdf
arihantmobileselepun
 
PDF
A geneticist is working with a new bacteriophage called phage Y3 that.pdf
arihantmobileselepun
 
PDF
Assume that the four living species in the figure below evolved from.pdf
arihantmobileselepun
 
PDF
Declining BalanceThe cost of the asset $10,000.00 The salvage v.pdf
arihantmobileselepun
 
PDF
Create a java project that - Draw a circle with three random init.pdf
arihantmobileselepun
 
PDF
aphase The spindle contracts and the sister chromatids are separated.pdf
arihantmobileselepun
 
PDF
A population of wild deer mice includes individuals with long or sho.pdf
arihantmobileselepun
 
PDF
Who is it important that the lymphatic system operate separately f.pdf
arihantmobileselepun
 
PDF
Provide a full explanation to the below question.1. Summarize the .pdf
arihantmobileselepun
 
PDF
Write a program to generate the entire calendar for one year. The pr.pdf
arihantmobileselepun
 
PDF
Write the interval notation for the set of numbers graphed. Solu.pdf
arihantmobileselepun
 
PDF
Why doesnt hemoglobin have any intermediate conformations between .pdf
arihantmobileselepun
 
PDF
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
arihantmobileselepun
 
PDF
Which of the following requires the mitochondria to create contact po.pdf
arihantmobileselepun
 
PDF
why nitrogen fixation is so importantSolutionNitrogen fixation.pdf
arihantmobileselepun
 
PDF
what will happen to the photon if two photons enter the same atom si.pdf
arihantmobileselepun
 
How are the epimysium and tendons relatedA. The epimysium surroun.pdf
arihantmobileselepun
 
How does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdf
arihantmobileselepun
 
Gerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdf
arihantmobileselepun
 
For Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdf
arihantmobileselepun
 
Find and provide a link to a multi-year capital plan from any Illino.pdf
arihantmobileselepun
 
A geneticist is working with a new bacteriophage called phage Y3 that.pdf
arihantmobileselepun
 
Assume that the four living species in the figure below evolved from.pdf
arihantmobileselepun
 
Declining BalanceThe cost of the asset $10,000.00 The salvage v.pdf
arihantmobileselepun
 
Create a java project that - Draw a circle with three random init.pdf
arihantmobileselepun
 
aphase The spindle contracts and the sister chromatids are separated.pdf
arihantmobileselepun
 
A population of wild deer mice includes individuals with long or sho.pdf
arihantmobileselepun
 
Who is it important that the lymphatic system operate separately f.pdf
arihantmobileselepun
 
Provide a full explanation to the below question.1. Summarize the .pdf
arihantmobileselepun
 
Write a program to generate the entire calendar for one year. The pr.pdf
arihantmobileselepun
 
Write the interval notation for the set of numbers graphed. Solu.pdf
arihantmobileselepun
 
Why doesnt hemoglobin have any intermediate conformations between .pdf
arihantmobileselepun
 
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
arihantmobileselepun
 
Which of the following requires the mitochondria to create contact po.pdf
arihantmobileselepun
 
why nitrogen fixation is so importantSolutionNitrogen fixation.pdf
arihantmobileselepun
 
what will happen to the photon if two photons enter the same atom si.pdf
arihantmobileselepun
 
Ad

Recently uploaded (20)

PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Geographical Diversity of India 100 Mcq.pdf/ 7th class new ncert /Social/Samy...
Sandeep Swamy
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
GRADE-3-PPT-EVE-2025-ENG-Q1-LESSON-1.pptx
EveOdrapngimapNarido
 
Ad

(1)Objective Binary Search Tree traversal (2 points)Use traversal.pdf

  • 1. (1)Objective: Binary Search Tree traversal (2 points) Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. I of BST have the same data from each input record. Download traversal-lab.pptx, inventory.txt, BinNode.java, BSTNode.java, BST.java, Dictionary.java . Perform specifications as follow: (a)Provide Add, Delete and Retrieve functions for user to access the database. Reject duplicate record when add a new record. (b)Modify BST.java to add printpostOrder, printpreOrder methods. (c)At the end, display inorder, postorder and preorder of the tree. Codes: /** Source code example for "A Practical Introduction to Data Structures and Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright 2008-2011 by Clifford A. Shaffer */ /** ADT for binary tree nodes */ public interface BinNode { /** Get and set the element value */ public E element(); public void setElement(E v); /** @return The left child */ public BinNode left(); /** @return The right child */ public BinNode right(); /** @return True if a leaf node, false otherwise */ public boolean isLeaf(); } //******************************************************************** // StringTree.java // //******************************************************************** import java.util.*; public class StringTree
  • 2. { private Node root; //---------------------------------------------------------------- // Creates an initially empty tree. //---------------------------------------------------------------- public StringTree() { root = null; } //---------------------------------------------------------------- // Adds a string to the tree. //---------------------------------------------------------------- public void addString (String str) { root = addStringToSubTree(str, root); } //---------------------------------------------------------------- // Adds a string to the subtree with the given root node //---------------------------------------------------------------- private Node addStringToSubTree (String str, Node node) { Node result = node; if (node == null) result = new Node(str); // If the new string comes before the string in the node, add // the new string to the left child. Otherwise, add it to the // right child. else if (str.compareTo(node.value) < 0) node.left = addStringToSubTree(str, node.left); else node.right = addStringToSubTree(str, node.right); return result; } //----------------------------------------------------------------
  • 3. // Prints the result of a depth-first traversal of the tree using // recursion. //---------------------------------------------------------------- public void traverseWithRecursion() { traverseWithRecursion(root); } //---------------------------------------------------------------- // Prints the elements in the specified tree using recursion. //---------------------------------------------------------------- private void traverseWithRecursion (Node node) { if (node != null) { traverseWithRecursion (node.left); System.out.print (node.value+" "); traverseWithRecursion (node.right); } } } //******************************************************************** // Node for a binary tree of Strings. //******************************************************************** class Node { public String value; public Node left; public Node right; public Node (String value) { this.value = value; this.left = left; this.right = right; } } /** Source code example for "A Practical Introduction to Data
  • 4. Structures and Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright 2008-2011 by Clifford A. Shaffer */ /** Binary tree node implementation: Pointers to children @param E The data element @param Key The associated key for the record */ import java.util.*; class BSTNode implements BinNode { private Key key; // Key for this node private E element; // Element for this node private BSTNode left; // Pointer to left child private BSTNode right; // Pointer to right child /** Constructors */ public BSTNode() {left = right = null; } public BSTNode(Key k, E val) { left = right = null; key = k; element = val; } public BSTNode(Key k, E val, BSTNode l, BSTNode r) { left = l; right = r; key = k; element = val; } /** Get and set the key value */ public Key key() { return key; } public void setKey(Key k) { key = k; } /** Get and set the element value */ public E element() { return element; } public void setElement(E v) { element = v; } /** Get and set the left child */ public BSTNode left() { return left; } public void setLeft(BSTNode p) { left = p; } /** Get and set the right child */ public BSTNode right() { return right; } public void setRight(BSTNode p) { right = p; } /** @return True if a leaf node, false otherwise */ public boolean isLeaf() { return (left == null) && (right == null); } }
  • 5. /** Source code example for "A Practical Introduction to Data Structures and Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright 2008-2011 by Clifford A. Shaffer */ import java.lang.Comparable; /** Binary Search Tree implementation for Dictionary ADT */ class BST, E> implements Dictionary { private BSTNode root; // Root of the BST int nodecount; // Number of nodes in the BST /** Constructor */ BST() { root = null; nodecount = 0; } /** Reinitialize tree */ public void clear() { root = null; nodecount = 0; } /** Insert a record into the tree. @param k Key value of the record. @param e The record to insert. */ public void insert(Key k, E e) { root = inserthelp(root, k, e); nodecount++; } // Return root public BSTNode getRoot() { return root; } /** Remove a record from the tree. @param k Key value of record to remove. @return The record removed, null if there is none. */ public E remove(Key k) { E temp = findhelp(root, k); // First find it if (temp != null) { root = removehelp(root, k); // Now remove it
  • 6. nodecount--; } return temp; } /** Remove and return the root node from the dictionary. @return The record removed, null if tree is empty. */ public E removeAny() { if (root == null) return null; E temp = root.element(); root = removehelp(root, root.key()); nodecount--; return temp; } /** @return Record with key value k, null if none exist. @param k The key value to find. */ public E find(Key k) { return findhelp(root, k); } /** @return The number of records in the dictionary. */ public int size() { return nodecount; } private E findhelp(BSTNode rt, Key k) { if (rt == null) return null; if (rt.key().compareTo(k) > 0) return findhelp(rt.left(), k); else if (rt.key().compareTo(k) == 0) return rt.element(); else return findhelp(rt.right(), k); } /** @return The current subtree, modified to contain the new item */ private BSTNode inserthelp(BSTNode rt, Key k, E e) { if (rt == null) return new BSTNode(k, e); if (rt.key().compareTo(k) > 0) rt.setLeft(inserthelp(rt.left(), k, e)); else rt.setRight(inserthelp(rt.right(), k, e)); return rt;
  • 7. } /** Remove a node with key value k @return The tree with the node removed */ private BSTNode removehelp(BSTNode rt,Key k) { if (rt == null) return null; if (rt.key().compareTo(k) > 0) rt.setLeft(removehelp(rt.left(), k)); else if (rt.key().compareTo(k) < 0) rt.setRight(removehelp(rt.right(), k)); else { // Found it if (rt.left() == null) return rt.right(); else if (rt.right() == null) return rt.left(); else { // Two children BSTNode temp = getmin(rt.right()); rt.setElement(temp.element()); rt.setKey(temp.key()); rt.setRight(deletemin(rt.right())); } } return rt; } private BSTNode getmin(BSTNode rt) { if (rt.left() == null) return rt; return getmin(rt.left()); } private BSTNode deletemin(BSTNode rt) { if (rt.left() == null) return rt.right(); rt.setLeft(deletemin(rt.left())); return rt; } private void printhelp(BSTNode rt) { if (rt == null) return; printhelp(rt.left()); printVisit(rt.element()); printhelp(rt.right());
  • 8. } private StringBuffer out; public String toString() { out = new StringBuffer(400); printhelp(root); return out.toString(); } private void printVisit(E it) { out.append(it + " "); } } /** Source code example for "A Practical Introduction to Data Structures and Algorithm Analysis, 3rd Edition (Java)" by Clifford A. Shaffer Copyright 2008-2011 by Clifford A. Shaffer */ /** The Dictionary abstract class. */ public interface Dictionary { /** Reinitialize dictionary */ public void clear(); /** Insert a record @param k The key for the record being inserted. @param e The record being inserted. */ public void insert(Key k, E e); /** Remove and return a record. @param k The key of the record to be removed. @return A maching record. If multiple records match "k", remove an arbitrary one. Return null if no record with key "k" exists. */ public E remove(Key k); /** Remove and return an arbitrary record from dictionary. @return the record removed, or null if none exists. */ public E removeAny(); /** @return A record matching "k" (null if none exists). If multiple records match, return an arbitrary one. @param k The key of the record to find */
  • 9. public E find(Key k); /** @return The number of records in the dictionary. */ public int size(); }; Text file : CT16C1288B DT14B1225F MI15B1250A MI15B1251A HO03N1095A HY07D1095BQ KI04D2593C DG12A1240AQ HY03G2593BQ TO30A1310A HO03N1095AQ HO01H1351C HO01H1350C FT18A1288B LR15A1000A BM12E1000A VW02B3113A NI23H1230AQ LX03D2503A LX03D2502A LX03D2502A VW22A3113B VW22B3113A Solution import java.util.Scanner; /* Class BSTNode */ class BSTNode {
  • 10. BSTNode left, right; int data; /* Constructor */ public BSTNode() { left = null; right = null; data = 0; } /* Constructor */ public BSTNode(int n) { left = null; right = null; data = n; } /* Function to set left node */ public void setLeft(BSTNode n) { left = n; } /* Function to set right node */ public void setRight(BSTNode n) { right = n; } /* Function to get left node */ public BSTNode getLeft() { return left; } /* Function to get right node */ public BSTNode getRight() { return right;
  • 11. } /* Function to set data to node */ public void setData(int d) { data = d; } /* Function to get data from node */ public int getData() { return data; } } /* Class BST */ class BST { private BSTNode root; /* Constructor */ public BST() { root = null; } /* Function to check if tree is empty */ public boolean isEmpty() { return root == null; } /* Functions to insert data */ public void insert(int data) { root = insert(root, data); } /* Function to insert data recursively */ private BSTNode insert(BSTNode node, int data) {
  • 12. if (node == null) node = new BSTNode(data); else { if (data <= node.getData()) node.left = insert(node.left, data); else node.right = insert(node.right, data); } return node; } /* Functions to delete data */ public void delete(int k) { if (isEmpty()) System.out.println("Tree Empty"); else if (search(k) == false) System.out.println("Sorry "+ k +" is not present"); else { root = delete(root, k); System.out.println(k+ " deleted from the tree"); } } private BSTNode delete(BSTNode root, int k) { BSTNode p, p2, n; if (root.getData() == k) { BSTNode lt, rt; lt = root.getLeft(); rt = root.getRight(); if (lt == null && rt == null) return null; else if (lt == null) {
  • 13. p = rt; return p; } else if (rt == null) { p = lt; return p; } else { p2 = rt; p = rt; while (p.getLeft() != null) p = p.getLeft(); p.setLeft(lt); return p2; } } if (k < root.getData()) { n = delete(root.getLeft(), k); root.setLeft(n); } else { n = delete(root.getRight(), k); root.setRight(n); } return root; } /* Functions to count number of nodes */ public int countNodes() { return countNodes(root); } /* Function to count number of nodes recursively */
  • 14. private int countNodes(BSTNode r) { if (r == null) return 0; else { int l = 1; l += countNodes(r.getLeft()); l += countNodes(r.getRight()); return l; } } /* Functions to search for an element */ public boolean search(int val) { return search(root, val); } /* Function to search for an element recursively */ private boolean search(BSTNode r, int val) { boolean found = false; while ((r != null) && !found) { int rval = r.getData(); if (val < rval) r = r.getLeft(); else if (val > rval) r = r.getRight(); else { found = true; break; } found = search(r, val); } return found;
  • 15. } /* Function for inorder traversal */ public void inorder() { inorder(root); } private void inorder(BSTNode r) { if (r != null) { inorder(r.getLeft()); System.out.print(r.getData() +" "); inorder(r.getRight()); } } /* Function for preorder traversal */ public void preorder() { preorder(root); } private void preorder(BSTNode r) { if (r != null) { System.out.print(r.getData() +" "); preorder(r.getLeft()); preorder(r.getRight()); } } /* Function for postorder traversal */ public void postorder() { postorder(root); } private void postorder(BSTNode r) {
  • 16. if (r != null) { postorder(r.getLeft()); postorder(r.getRight()); System.out.print(r.getData() +" "); } } } /* Class BinarySearchTree */ public class BinarySearchTree { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /* Creating object of BST */ BST bst = new BST(); System.out.println("Binary Search Tree Test "); char ch; /* Perform tree operations */ do { System.out.println(" Binary Search Tree Operations "); System.out.println("1. insert "); System.out.println("2. delete"); System.out.println("3. search"); System.out.println("4. count nodes"); System.out.println("5. check empty"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); bst.insert( scan.nextInt() ); break;
  • 17. case 2 : System.out.println("Enter integer element to delete"); bst.delete( scan.nextInt() ); break; case 3 : System.out.println("Enter integer element to search"); System.out.println("Search result : "+ bst.search( scan.nextInt() )); break; case 4 : System.out.println("Nodes = "+ bst.countNodes()); break; case 5 : System.out.println("Empty status = "+ bst.isEmpty()); break; default : System.out.println("Wrong Entry "); break; } /* Display tree */ System.out.print(" Post order : "); bst.postorder(); System.out.print(" Pre order : "); bst.preorder(); System.out.print(" In order : "); bst.inorder(); System.out.println(" Do you want to continue (Type y or n) "); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } }