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

In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
adityastores21
 
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
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
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
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
ARCHANASTOREKOTA
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
anukoolelectronics
 
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
 
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
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfC++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
rohit219406
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
Programming Homework Help
 
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
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
Inheritance compiler support
Inheritance compiler supportInheritance compiler support
Inheritance compiler support
Syed Zaid Irshad
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdfcreate a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
Javascript
JavascriptJavascript
Javascript
Vlad Ifrim
 

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

In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
 
MAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdfMAINCPP include ltiostreamgt include ltstringgt u.pdf
MAINCPP include ltiostreamgt include ltstringgt u.pdf
 
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
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
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
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
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
 
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
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfC++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
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
 
SQLite Techniques
SQLite TechniquesSQLite Techniques
SQLite Techniques
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Inheritance compiler support
Inheritance compiler supportInheritance compiler support
Inheritance compiler support
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdfcreate a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
 
Javascript
JavascriptJavascript
Javascript
 

More from arihantmobileselepun

How are the epimysium and tendons relatedA. The epimysium surroun.pdf
How are the epimysium and tendons relatedA. The epimysium surroun.pdfHow are the epimysium and tendons relatedA. The epimysium surroun.pdf
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
How does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdfHow does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdf
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
Gerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdfGerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdf
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
For Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdfFor Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdf
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
Find and provide a link to a multi-year capital plan from any Illino.pdfFind and provide a link to a multi-year capital plan from any Illino.pdf
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
A geneticist is working with a new bacteriophage called phage Y3 that.pdfA geneticist is working with a new bacteriophage called phage Y3 that.pdf
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
Assume that the four living species in the figure below evolved from.pdfAssume that the four living species in the figure below evolved from.pdf
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
Declining BalanceThe cost of the asset $10,000.00 The salvage v.pdfDeclining BalanceThe cost of the asset $10,000.00 The salvage v.pdf
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
Create a java project that - Draw a circle with three random init.pdfCreate a java project that - Draw a circle with three random init.pdf
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
aphase The spindle contracts and the sister chromatids are separated.pdfaphase The spindle contracts and the sister chromatids are separated.pdf
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
A population of wild deer mice includes individuals with long or sho.pdfA population of wild deer mice includes individuals with long or sho.pdf
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
Who is it important that the lymphatic system operate separately f.pdfWho is it important that the lymphatic system operate separately f.pdf
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
Provide a full explanation to the below question.1. Summarize the .pdfProvide a full explanation to the below question.1. Summarize the .pdf
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
Write a program to generate the entire calendar for one year. The pr.pdfWrite a program to generate the entire calendar for one year. The pr.pdf
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
Write the interval notation for the set of numbers graphed.  Solu.pdfWrite the interval notation for the set of numbers graphed.  Solu.pdf
Write the interval notation for the set of numbers graphed. Solu.pdf
arihantmobileselepun
 
Hyenas are diploid organisms, and their gametes contain 20 chromosome.pdf
Hyenas are diploid organisms, and their gametes contain 20 chromosome.pdfHyenas are diploid organisms, and their gametes contain 20 chromosome.pdf
Hyenas are diploid organisms, and their gametes contain 20 chromosome.pdf
arihantmobileselepun
 
Why doesnt hemoglobin have any intermediate conformations between .pdf
Why doesnt hemoglobin have any intermediate conformations between .pdfWhy doesnt hemoglobin have any intermediate conformations between .pdf
Why doesnt hemoglobin have any intermediate conformations between .pdf
arihantmobileselepun
 
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
arihantmobileselepun
 
Which of the following requires the mitochondria to create contact po.pdf
Which of the following requires the mitochondria to create contact po.pdfWhich of the following requires the mitochondria to create contact po.pdf
Which of the following requires the mitochondria to create contact po.pdf
arihantmobileselepun
 
why nitrogen fixation is so importantSolutionNitrogen fixation.pdf
why nitrogen fixation is so importantSolutionNitrogen fixation.pdfwhy nitrogen fixation is so importantSolutionNitrogen fixation.pdf
why nitrogen fixation is so importantSolutionNitrogen fixation.pdf
arihantmobileselepun
 

More from arihantmobileselepun (20)

How are the epimysium and tendons relatedA. The epimysium surroun.pdf
How are the epimysium and tendons relatedA. The epimysium surroun.pdfHow are the epimysium and tendons relatedA. The epimysium surroun.pdf
How are the epimysium and tendons relatedA. The epimysium surroun.pdf
 
How does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdf
How does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdfHow does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdf
How does DNA differ from RNAA. RNA uses only purinesB. RNA uses.pdf
 
Gerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdf
Gerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdfGerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdf
Gerard throws a discus distances of 10 meters, 14.5 meters, 14.8 met.pdf
 
For Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdf
For Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdfFor Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdf
For Printing and personal use ONLY. DO NOT Hand in this copy of the a.pdf
 
Find and provide a link to a multi-year capital plan from any Illino.pdf
Find and provide a link to a multi-year capital plan from any Illino.pdfFind and provide a link to a multi-year capital plan from any Illino.pdf
Find and provide a link to a multi-year capital plan from any Illino.pdf
 
A geneticist is working with a new bacteriophage called phage Y3 that.pdf
A geneticist is working with a new bacteriophage called phage Y3 that.pdfA geneticist is working with a new bacteriophage called phage Y3 that.pdf
A geneticist is working with a new bacteriophage called phage Y3 that.pdf
 
Assume that the four living species in the figure below evolved from.pdf
Assume that the four living species in the figure below evolved from.pdfAssume that the four living species in the figure below evolved from.pdf
Assume that the four living species in the figure below evolved from.pdf
 
Declining BalanceThe cost of the asset $10,000.00 The salvage v.pdf
Declining BalanceThe cost of the asset $10,000.00 The salvage v.pdfDeclining BalanceThe cost of the asset $10,000.00 The salvage v.pdf
Declining BalanceThe cost of the asset $10,000.00 The salvage v.pdf
 
Create a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdfCreate a java project that - Draw a circle with three random init.pdf
Create a java project that - Draw a circle with three random init.pdf
 
aphase The spindle contracts and the sister chromatids are separated.pdf
aphase The spindle contracts and the sister chromatids are separated.pdfaphase The spindle contracts and the sister chromatids are separated.pdf
aphase The spindle contracts and the sister chromatids are separated.pdf
 
A population of wild deer mice includes individuals with long or sho.pdf
A population of wild deer mice includes individuals with long or sho.pdfA population of wild deer mice includes individuals with long or sho.pdf
A population of wild deer mice includes individuals with long or sho.pdf
 
Who is it important that the lymphatic system operate separately f.pdf
Who is it important that the lymphatic system operate separately f.pdfWho is it important that the lymphatic system operate separately f.pdf
Who is it important that the lymphatic system operate separately f.pdf
 
Provide a full explanation to the below question.1. Summarize the .pdf
Provide a full explanation to the below question.1. Summarize the .pdfProvide a full explanation to the below question.1. Summarize the .pdf
Provide a full explanation to the below question.1. Summarize the .pdf
 
Write a program to generate the entire calendar for one year. The pr.pdf
Write a program to generate the entire calendar for one year. The pr.pdfWrite a program to generate the entire calendar for one year. The pr.pdf
Write a program to generate the entire calendar for one year. The pr.pdf
 
Write the interval notation for the set of numbers graphed. Solu.pdf
Write the interval notation for the set of numbers graphed.  Solu.pdfWrite the interval notation for the set of numbers graphed.  Solu.pdf
Write the interval notation for the set of numbers graphed. Solu.pdf
 
Hyenas are diploid organisms, and their gametes contain 20 chromosome.pdf
Hyenas are diploid organisms, and their gametes contain 20 chromosome.pdfHyenas are diploid organisms, and their gametes contain 20 chromosome.pdf
Hyenas are diploid organisms, and their gametes contain 20 chromosome.pdf
 
Why doesnt hemoglobin have any intermediate conformations between .pdf
Why doesnt hemoglobin have any intermediate conformations between .pdfWhy doesnt hemoglobin have any intermediate conformations between .pdf
Why doesnt hemoglobin have any intermediate conformations between .pdf
 
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
4. What is gyanandromorphy How does this happenSolutionAnswe.pdf
 
Which of the following requires the mitochondria to create contact po.pdf
Which of the following requires the mitochondria to create contact po.pdfWhich of the following requires the mitochondria to create contact po.pdf
Which of the following requires the mitochondria to create contact po.pdf
 
why nitrogen fixation is so importantSolutionNitrogen fixation.pdf
why nitrogen fixation is so importantSolutionNitrogen fixation.pdfwhy nitrogen fixation is so importantSolutionNitrogen fixation.pdf
why nitrogen fixation is so importantSolutionNitrogen fixation.pdf
 

Recently uploaded

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
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
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
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
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
 

Recently uploaded (20)

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
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......Ethnobotany and Ethnopharmacology ......
Ethnobotany and Ethnopharmacology ......
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
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
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
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
 

(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'); } }