SlideShare a Scribd company logo
1 of 11
Download to read offline
Objective: Binary Search Tree traversal (2 points)
Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. Input
records from inventory.txt. Both key and Element of BST have the same data from each input
record.
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();
}
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 + " ");
}
}
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); }
}
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();
};
//
inventory.txt
traverse
CT16C1288B
DT14B1225F
MI15B1250A
MI15B1251A
HO03N1095A
HY07D1095BQ
KI04D2593C
DG12A1240AQ
HY03G2593BQ
TO30A1310A
HO03N1095AQ
HO01H1351C
HO01H1350C
FT18A1288B
LR15A1000A
BM12E1000A
VW02B3113A
NI23H1230AQ
LX03D2503A
LX03D2502A
LX03D2502A
VW22A3113B
VW22B3113A
Solution
public class BST implements Dictionary {
BSTNode root; // the root of the BST.
// constructor
public BST() {
this(null);
}
// parametrized constructor
public BST(BSTNode root) {
this.root = root;
}
// arranging nodes when cases like deleting node
public BSTNode MinAttach(BSTNode right, BSTNode left) {
if(right.getLeft() == null) {
right.setLeft(left);
return right;
}
else {
right.setLeft(MinAttach(right.getLeft(), left));
return right;
}
}
// deleting entry ..passing key
public void delete(K key) {
this.root = deleteNodeRecursively(root, key);
}
// deleting nodes
public BSTNode DeleteDoubNode(BSTNode node) {
if(node.getLeft() == null) {
//at the bottom of the nodes.
return node.getRight();
}
else {
//set the left node as the right of the one we found at the bottom.
node.setLeft(DeleteDoubNode(node.getLeft()));
}
return node;
}
// recursively deleting node
public BSTNode deleteNodeRecursively(BSTNode node, K key) {
// check right node to delete
if(key.compareTo(node.getKey()) == 0) {
// check for leaf
if((node.getLeft() == null) && (node.getRight() == null)) {
return null;
}
//check node with right child
else if((node.getLeft() == null) && (node.getRight() != null)) {
return node.getRight();
}
//check node with left child
else if((node.getLeft() != null) && (node.getRight() == null)) {
return node.getLeft();
}
// check node with two children
else if((node.getLeft() != null) && (node.getRight() != null)) {
BSTNode replacementNode = findMin(node.getRight());
BSTNode backupLeft = node.getLeft();
replacementNode.setRight(DeleteDoubNode(node.getRight()));
replacementNode.setLeft(backupLeft);
return replacementNode;
}
else {
return node;
}
}
//check key is less than
else if(key.compareTo(node.getKey()) < 0) {
if(node.getLeft() != null) {
node.left = deleteNodeRecursively(node.getLeft(), key);
return node;
}
}
//check key is greater than
else {
if(node.getRight() != null) {
node.right = deleteNodeRecursively(node.getRight(), key);
return node;
}
}
return node;
}
// returns depth of tree
public int depth() {
return depthPostOrder(root, 0);
}
// find minimum value of BST
public BSTNode findMin(BSTNode node) {
while(node.getLeft() != null) {
node = node.getLeft();
}
return node;
}
// BST inorder
public void inorder(BSTNode node) {
if(node != null) {
inorder(node.getLeft()); //get first left keys
System.out.println("key: " + node.getKey().toString() + " element: " +
node.getElement().toString());
inorder(node.getRight());
}
}
// inserting new element
public void insert(K key, E element) {
if(root == null) {
root = new BSTNode(key, element, null, null);
}
else {
insertBelow(root, key, element);
}
}
// recursive preorder depth
int depthPostOrder(BSTNode node, int current_depth) {
if(node != null) {return Math.max(depthPostOrder(node.getLeft(), current_depth+1),
depthPostOrder(node.getRight(), current_depth+1));
}
else return current_depth;
}
// printing whole tree
public void printTree() {
//printing recursively
System.out.println(" Outputting BSTree...");
inorder(root);
}
// serach method
public E search(K key) {
BSTNode nodeFound;
nodeFound = searchingNode(key);
if(nodeFound == null) {
return null; //not found
}
else return searchingNode(key).getElement(); //call another helper method.
}
// searching node
public BSTNode searchingNode(K key) {
if(key == null) {
return null;
}
if(root == null) {
return null; //if empty tree
}
//if both keys are equal
if(key.compareTo(root.getKey()) == 0) {
return root;
}
//less than root key
else if(key.compareTo(root.getKey()) < 0) {
return searchBelow(root.getLeft(), key); //call the recursive search method.
}
//greater than root key
else if(key.compareTo(root.getKey()) > 0) {
return searchBelow(root.getRight(), key); //call the recursive search method.
}
else {
System.out.println("ERROR occured");
return null;
}
}
}

More Related Content

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

5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
rambagra74
 
Javai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdfJavai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdf
stopgolook
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
info750646
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
erremmfab
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
aksahnan
 
There is BinarySearchTree class. When removing a node from a BST, we.pdf
There is BinarySearchTree class. When removing a node from a BST, we.pdfThere is BinarySearchTree class. When removing a node from a BST, we.pdf
There is BinarySearchTree class. When removing a node from a BST, we.pdf
Dhanrajsolanki2091
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
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
 
Tree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfTree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdf
ajayadinathcomputers
 
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
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
rohit219406
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdf
feelingcomputors
 
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
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
malavshah9013
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
KUNALHARCHANDANI1
 

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

5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
5. Design and implement a method contains 2 for BinarySearchTree, fu.pdf
 
Javai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdfJavai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdf
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
 
create a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdfcreate a binary search tree from an empty one by adding the key valu.pdf
create a binary search tree from an empty one by adding the key valu.pdf
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
So I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdfSo I have this code(StackInAllSocks) and I implemented the method but.pdf
So I have this code(StackInAllSocks) and I implemented the method but.pdf
 
There is BinarySearchTree class. When removing a node from a BST, we.pdf
There is BinarySearchTree class. When removing a node from a BST, we.pdfThere is BinarySearchTree class. When removing a node from a BST, we.pdf
There is BinarySearchTree class. When removing a node from a BST, we.pdf
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .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
 
Tree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.pdfTree Traversals A tree traversal is the process of visiting.pdf
Tree Traversals A tree traversal is the process of visiting.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
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
 
How to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.pdfHow to do the main method for this programBinaryNode.javapublic.pdf
How to do the main method for this programBinaryNode.javapublic.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
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
The LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdfThe LinkedList1 class implements a Linked list. class.pdf
The LinkedList1 class implements a Linked list. class.pdf
 
Describe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdfDescribe an algorithm for concatenating two singly linked lists L and.pdf
Describe an algorithm for concatenating two singly linked lists L and.pdf
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
 
Binary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structureBinary Tree in C++ coding in the data structure
Binary Tree in C++ coding in the data structure
 

More from sivakumar19831

Problem I. As shown in the pedigree below, a pair of first cousins (.pdf
Problem I. As shown in the pedigree below, a pair of first cousins (.pdfProblem I. As shown in the pedigree below, a pair of first cousins (.pdf
Problem I. As shown in the pedigree below, a pair of first cousins (.pdf
sivakumar19831
 
Points are assigned both on the correctness of the answer and the com.pdf
Points are assigned both on the correctness of the answer and the com.pdfPoints are assigned both on the correctness of the answer and the com.pdf
Points are assigned both on the correctness of the answer and the com.pdf
sivakumar19831
 
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdf
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdfOn January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdf
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdf
sivakumar19831
 
Objectives 1. Understand the design, implementation, usage and limita.pdf
Objectives 1. Understand the design, implementation, usage and limita.pdfObjectives 1. Understand the design, implementation, usage and limita.pdf
Objectives 1. Understand the design, implementation, usage and limita.pdf
sivakumar19831
 
New Nirvana Ltd is a company controlled by the members of the hard r.pdf
New Nirvana Ltd is a company controlled by the members of the hard r.pdfNew Nirvana Ltd is a company controlled by the members of the hard r.pdf
New Nirvana Ltd is a company controlled by the members of the hard r.pdf
sivakumar19831
 
Malaria being spread by mosquitoes is an example of which type of dis.pdf
Malaria being spread by mosquitoes is an example of which type of dis.pdfMalaria being spread by mosquitoes is an example of which type of dis.pdf
Malaria being spread by mosquitoes is an example of which type of dis.pdf
sivakumar19831
 
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdf
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdfIn oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdf
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdf
sivakumar19831
 
List and define the significance of the following proteinsstructures.pdf
List and define the significance of the following proteinsstructures.pdfList and define the significance of the following proteinsstructures.pdf
List and define the significance of the following proteinsstructures.pdf
sivakumar19831
 

More from sivakumar19831 (11)

Problem I. As shown in the pedigree below, a pair of first cousins (.pdf
Problem I. As shown in the pedigree below, a pair of first cousins (.pdfProblem I. As shown in the pedigree below, a pair of first cousins (.pdf
Problem I. As shown in the pedigree below, a pair of first cousins (.pdf
 
Points are assigned both on the correctness of the answer and the com.pdf
Points are assigned both on the correctness of the answer and the com.pdfPoints are assigned both on the correctness of the answer and the com.pdf
Points are assigned both on the correctness of the answer and the com.pdf
 
Predefined Characters in C Type. Please make sure the program compil.pdf
Predefined Characters in C Type. Please make sure the program compil.pdfPredefined Characters in C Type. Please make sure the program compil.pdf
Predefined Characters in C Type. Please make sure the program compil.pdf
 
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdf
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdfOn January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdf
On January 1, 2017, Pinnacle Corporation exchanged $3,527,500 cash f.pdf
 
Most of the functions of a cell membrane are performed by proteins ch.pdf
Most of the functions of a cell membrane are performed by proteins ch.pdfMost of the functions of a cell membrane are performed by proteins ch.pdf
Most of the functions of a cell membrane are performed by proteins ch.pdf
 
Objectives 1. Understand the design, implementation, usage and limita.pdf
Objectives 1. Understand the design, implementation, usage and limita.pdfObjectives 1. Understand the design, implementation, usage and limita.pdf
Objectives 1. Understand the design, implementation, usage and limita.pdf
 
New Nirvana Ltd is a company controlled by the members of the hard r.pdf
New Nirvana Ltd is a company controlled by the members of the hard r.pdfNew Nirvana Ltd is a company controlled by the members of the hard r.pdf
New Nirvana Ltd is a company controlled by the members of the hard r.pdf
 
Malaria being spread by mosquitoes is an example of which type of dis.pdf
Malaria being spread by mosquitoes is an example of which type of dis.pdfMalaria being spread by mosquitoes is an example of which type of dis.pdf
Malaria being spread by mosquitoes is an example of which type of dis.pdf
 
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdf
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdfIn oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdf
In oxidative phosphorylation and phosphorylation, the enzyme ATP synt.pdf
 
List and define the significance of the following proteinsstructures.pdf
List and define the significance of the following proteinsstructures.pdfList and define the significance of the following proteinsstructures.pdf
List and define the significance of the following proteinsstructures.pdf
 
In this TEM image, what does the TEM allow you to view that would no.pdf
In this TEM image, what does the TEM allow you to view that would no.pdfIn this TEM image, what does the TEM allow you to view that would no.pdf
In this TEM image, what does the TEM allow you to view that would no.pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 

Recently uploaded (20)

Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 

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

  • 1. Objective: Binary Search Tree traversal (2 points) Use traversal.pptx as guidance to write a program to build a binary search tree Dictionary. Input records from inventory.txt. Both key and Element of BST have the same data from each input record. 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(); } 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() {
  • 2. 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); }
  • 3. /** @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()); }
  • 4. 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 + " "); } } 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; }
  • 5. /** 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); } } 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(); };
  • 7. // parametrized constructor public BST(BSTNode root) { this.root = root; } // arranging nodes when cases like deleting node public BSTNode MinAttach(BSTNode right, BSTNode left) { if(right.getLeft() == null) { right.setLeft(left); return right; } else { right.setLeft(MinAttach(right.getLeft(), left)); return right; } } // deleting entry ..passing key public void delete(K key) { this.root = deleteNodeRecursively(root, key); } // deleting nodes public BSTNode DeleteDoubNode(BSTNode node) { if(node.getLeft() == null) { //at the bottom of the nodes. return node.getRight(); } else { //set the left node as the right of the one we found at the bottom. node.setLeft(DeleteDoubNode(node.getLeft())); } return node; } // recursively deleting node public BSTNode deleteNodeRecursively(BSTNode node, K key) { // check right node to delete if(key.compareTo(node.getKey()) == 0) { // check for leaf
  • 8. if((node.getLeft() == null) && (node.getRight() == null)) { return null; } //check node with right child else if((node.getLeft() == null) && (node.getRight() != null)) { return node.getRight(); } //check node with left child else if((node.getLeft() != null) && (node.getRight() == null)) { return node.getLeft(); } // check node with two children else if((node.getLeft() != null) && (node.getRight() != null)) { BSTNode replacementNode = findMin(node.getRight()); BSTNode backupLeft = node.getLeft(); replacementNode.setRight(DeleteDoubNode(node.getRight())); replacementNode.setLeft(backupLeft); return replacementNode; } else { return node; } } //check key is less than else if(key.compareTo(node.getKey()) < 0) { if(node.getLeft() != null) { node.left = deleteNodeRecursively(node.getLeft(), key); return node; } } //check key is greater than else { if(node.getRight() != null) { node.right = deleteNodeRecursively(node.getRight(), key); return node; }
  • 9. } return node; } // returns depth of tree public int depth() { return depthPostOrder(root, 0); } // find minimum value of BST public BSTNode findMin(BSTNode node) { while(node.getLeft() != null) { node = node.getLeft(); } return node; } // BST inorder public void inorder(BSTNode node) { if(node != null) { inorder(node.getLeft()); //get first left keys System.out.println("key: " + node.getKey().toString() + " element: " + node.getElement().toString()); inorder(node.getRight()); } } // inserting new element public void insert(K key, E element) { if(root == null) { root = new BSTNode(key, element, null, null); } else { insertBelow(root, key, element); } } // recursive preorder depth int depthPostOrder(BSTNode node, int current_depth) { if(node != null) {return Math.max(depthPostOrder(node.getLeft(), current_depth+1),
  • 10. depthPostOrder(node.getRight(), current_depth+1)); } else return current_depth; } // printing whole tree public void printTree() { //printing recursively System.out.println(" Outputting BSTree..."); inorder(root); } // serach method public E search(K key) { BSTNode nodeFound; nodeFound = searchingNode(key); if(nodeFound == null) { return null; //not found } else return searchingNode(key).getElement(); //call another helper method. } // searching node public BSTNode searchingNode(K key) { if(key == null) { return null; } if(root == null) { return null; //if empty tree } //if both keys are equal if(key.compareTo(root.getKey()) == 0) { return root; } //less than root key else if(key.compareTo(root.getKey()) < 0) { return searchBelow(root.getLeft(), key); //call the recursive search method. }
  • 11. //greater than root key else if(key.compareTo(root.getKey()) > 0) { return searchBelow(root.getRight(), key); //call the recursive search method. } else { System.out.println("ERROR occured"); return null; } } }