Question

In need of JAVA CODE FOR THIS OBJECTIVE: Modify the BST class I gave you as...

In need of JAVA CODE FOR THIS 

OBJECTIVE:

Modify the BST class I gave you as follows:
In the case in which the deleted node has two children, write the code in 
two ways. 

a) always replace the deleted node with the largest node on the left.
b) count how many deletions have been done, and for even deletions
replace the deleted node with the largest node on the left, for odd
deletions, replace the deleted node with the smallest node on the right.


Now do an experiment in which you add 100 random Doubles to the tree, then
repeatedly delete and add values many times. (Keep an array of the numbers currently in the tree and randomly choose an element of the array to delete.)

As you do each random deletion and insertion, note the depth of the tree, and
create a graph (using Excel?) that shows how the tree's depth changes.

Do this epxperiment for each of the deletion strategies a) and b).  How do
the graphs differ?

To generate the random numbers needed,

import java.util.Random;
then in your code,

Random ran = new Random();
ran.nextDouble(); gives a double between 0.0 and 1.0
ran.nextInt(n) gives a random integer between 0 and n-1 inclusive

BST CLASS:

public class BST<T extends Comparable<T>> 
{
  private Node<T> root;

  public BST()
  {
    this.root = null;
  }

  public void insert(T datum) throws BSTException
  {
    this.root = insert(this.root, datum);
  }

  private Node<T> insert(Node<T> r, T datum) throws BSTException
  {
    if( r == null)
    {
      return new Node<T>(datum);
    }
    else
    {
      int sign = r.getData().compareTo(datum);
      if(sign == 0)
      {
        throw new BSTException("Duplicate Entry " + datum);
      }
      else if(sign > 0)
      {
        r.setLeft(insert(r.getLeft(), datum));
      }
      else
      {
        r.setRight(insert(r.getRight(), datum));
      }
      return r;
    }
  }

  public T lookup(T target)
  {
    Node<T> where = root;
    T retval = null;

    while (where != null && retval == null)
    {
      int sign = where.getData().compareTo(target);
      if (sign == 0)
        retval = where.getData();
      else if(sign > 0)
        where = where.getLeft();
      else
        where = where.getRight();
    }
    return retval;
  }
 
  public void delete(T target)
  {
    root = delete(root, target);
    return;
  }

  private Node<T> delete(Node<T> root, T target)
  {
    //Tree is empty
    if (root == null)
      return root;
    // if not empty tree, search recursively for target
    int sign = target.compareTo(root.getData());
    if (sign < 0) //go left
      root.setLeft(delete(root.getLeft(), target));
    else if (sign > 0) //go right
      root.setRight(delete(root.getRight(), target));
    else // sign == 0 so we found it 
    {
      //case 1 and 2: 0 or 1 child
      if (root.getLeft() == null)
        return root.getRight();
      else if (root.getRight() == null)
        return root.getLeft();

      //if we get here, there are 2 children.
      //replace our data with minimum data 
      //in right subtree
      root.setData(minOnRight(root.getRight()));
      //or with maximum data in left subtree
      //root.setData(maxOnLeft(root.getLeft());
      
      //finally, delete the node whose data we
      //copied 
      root.setRight(delete(root.getRight(), root.getData()));
    }
    return root;
  }
      
  private T minOnRight(Node<T> r)
  {
    while(r.getLeft() != null)
      r = r.getLeft();
    return r.getData();
  }

  public int getDepth()
  {
    return getDepth(root);
  }

  public int getDepth(Node<T> r)
  {
    int retval = -1;
    if (r == null)
      return retval;
    else 
    {
      retval = Math.max(getDepth(r.getLeft()), getDepth(r.getRight()) ) + 1;
    }
    return retval;
  }

  public String toString()
  {
    String retval = "";
    return toString(root, retval);
  }

  public String toString(Node<T> r, String retval)
  {
    if (r == null)
    {
      return retval + "null" + "\n";
    }
    else
    {
      retval += r.getData() + "\n";
      retval = toString(r.getLeft(), retval);
      retval = toString(r.getRight(), retval);
    }
    return retval;
  }

  public static void main(String args[]) throws BSTException
  {
    BST<String> sbst = new BST<String>();
    sbst.insert("horse");
    sbst.insert("cow");
    sbst.insert("manticore");
    sbst.insert("jaguar");
    sbst.insert("zebra");
    sbst.insert("aardvark");
    sbst.insert("duck");
    System.out.println(sbst);
    System.out.println();
    sbst.delete("horse");
    System.out.println(sbst);
  }
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution:
...............................................................................................................................................................

package bst;

import javafx.scene.Node;
import java.util.Random;
import java.util.Arrays;


public class BST<T extends Comparable<T>>
{
private Node<T> root;

public BST()
{
    this.root = null;
}
  
public boolean whetherEmpty() {
    
      if ( root == null)
            return true;
      else
            return false;
      // technically the same effect as the following short and sweet line
      // return root == null;
    
} // end function whether empty or not

public void findDepth () {
      // recursive function to find the depth of the tree
  
      // generating 100 random doubles and adding them to the tree to hold them
      double [] tempTree = new double[100];
      Random rn = new Random();     // rn = random number
      double r;
      for (int i = 0; i<100; i++)   {
          //int r = rn.nextInt(); // r = random value
          r = rn.nextDouble();
          System.out.println("Adding the random double value" + (r) + " to the tree");
      } // end for
      //
    
    
} // end function findDepth

public void insert(T datum) throws BSTException
{
    this.root = recInsert(this.root, datum);
    // insert recursively into the BS Tree
}

private Node<T> recInsert(Node<T> r, T datum)
throws BSTException
{
    if( r == null)
    {
      return new Node<T>(datum);
    } // end of then condition
    else
    {
      int sign = r.getData().compareTo(datum);
      if(sign == 0)
      {
        throw new BSTException("Duplicate Entry " +
datum);
      }
      else if(sign > 0)
      { // deal with the left sub tree
        r.setLeft(recInsert(r.getLeft(), datum));
      }
      else
      { // focus on the right sub tree
        r.setRight(recInsert(r.getRight(), datum));
      }
      return r;
    }
}

public T lookup(T target)
{
    Node<T> where = root;
    T retval = null;

    while (where != null && retval == null)
    {
      int sign = where.getData().compareTo(target);
      if (sign == 0)
        retval = where.getData();
      else if(sign > 0)
        where = where.getLeft();
      else
        where = where.getRight();
    }
    return retval;
}

public T delete(T target)
{
    //to be written
    
      // the delete method or function
    
      if ( (whetherEmpty())) {
          System.out.println("Sorry, the tree seems to be empty or null - please add some nodes and then try this option again, thanks......");
          else if (seek(target) == false )   // seek - you (thou) shall find the node to be deleted !!!!!
              System.out.println("Oops, you do not have to over kill - the node " + (target) + " you are trying to delete is not there first of all \n please do not beat a dead snake - try to delete some other existing node.....");
          else { // finalyy can delete successfully
                  root = delete (root, target);
                  System.out.println(target + " had been got rid off from the tree");
                  } // end else
      } // end if
    
      // (a) Replace the deleted node with the largest node on the left
    
    
    
    
      // [b] count the number of deletions
    
      // for each even deletion, replace the deleted nde with the largest node on the left
    
    
      // for each odd deletion, replace teh deleted node with the smallest node on the right
    
    
      // hence it is the largest left and smallest right for even and odd respectively
    
    
    
    
    return target;
}

public String toString()
{
    String retval = "";
    return recToString(root, retval);
}

    /**
     *
     * @param r
     * @param retval
     * @return
     */
    public String recToString(Node<T> r, String retval)
{
    if (r == null)
    {
      return retval + "null" + "\n";
    }
    else
    {
      retval += r.getData() + "\n";
      retval = recToString(r.getLeft(), retval);
      retval = recToString(r.getRight(), retval);
    }
    return retval;
}

public static void main(String args[]) throws
BSTException
{
    BST<Integer> sbst = new BST<Integer>();

 sbst.insert("horse");
    sbst.insert("cow");
    sbst.insert("manticore");
    sbst.insert("jaguar");
    sbst.insert("zebra");
    sbst.insert("aardvark");
    sbst.insert("duck");
    System.out.println(sbst);
    System.out.println();
    sbst.delete("horse");
    System.out.println(sbst);



}

    private static class BSTException extends Exception {

        public BSTException() {
        }

        private BSTException(String string) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }
}

Add a comment
Know the answer?
Add Answer to:
In need of JAVA CODE FOR THIS OBJECTIVE: Modify the BST class I gave you as...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • hi, I am suppose to implement that method in java for bst but the result doesn't...

    hi, I am suppose to implement that method in java for bst but the result doesn't work as excpected * _Part 8: Implement this method._ * * toString() is a method defined by Java's Object class * that can be used to provide a String representation for your * class. It is called anytime you concatenate an Object to * a String. * * Build a string representation of the BST that describes both * the values stored inside and...

  • Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to com...

    Please I need help ASAP Java Programing: Binary Search Tree Fully implement the BST class in Listing 25.4 (on page 961 of the 11th Edition of the text). Design and write a (main) driver program to completely test every method in the BST class to ensure the class meets all its requirements. You should read the Listing 25.5: TestBST.java for an idea of what your program should look like. Listing 25.4 BST.java public class BST> extends AbstractTree { protected TreeNode...

  • public class Buildbst { private int data; private Buildbst left; private Buildbst right; //Set the binary...

    public class Buildbst { private int data; private Buildbst left; private Buildbst right; //Set the binary search tree public Buildbst(int data) { this.data = data; this.left = null; this.right =null; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Buildbst getLeft() { return left; } public void setLeft(Buildbst left) { this.left = left; } public Buildbst getRight() { return right; } public void setRight(Buildbst right) { this.right = right; } }...

  • Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException;...

    Professionally and thoroughly comment on this code. //BinarySearchTree.java package Project.bst; //imports required import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; class BSTTreeNode{    BSTTreeNode left, right;    String data; public BSTTreeNode(){    left = null;    right = null;    data = null; } public BSTTreeNode(String n){    left = null;    right = null;    data = n; } public void setLeft(BSTTreeNode n){    left = n; } public void setRight(BSTTreeNode n){   ...

  • Question B1 You are given the following Java classes: public class Queue { private static class...

    Question B1 You are given the following Java classes: public class Queue { private static class Node { Object object; Node next; Node () { object = null; next = null; } Node (Object object, Node next) { this.object = object; this.next = next; private Node header; private int size = 0; // size shows the no of elements in queue public Object dequeue () { if (size == 0 ) { return null; else { Object remove_object = header.object;...

  • Please implement a right rotation funtion: private Node rightRotate(Node root) { } Remember to return the...

    Please implement a right rotation funtion: private Node rightRotate(Node root) { } Remember to return the new root of the subtree to the parent so the parent can set it to be its child package trees; public class BinaryTree> { private Node root; //private int size; public static int sumTree(Node root) { if(root== null) { return 0; } int center = 0; if( root.item % 2 == 0) { center = root.item; } int left = sumTree(root.left); int right =...

  • BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E>...

    BST JAVA FILE import java.util.*; public class BST <E extends Comparable <E>> {    private TreeNode<E> overallRoot;    public BST() {        overallRoot = null;    }    // ************ ADD ************ //    public void add(E addThis) {        if (overallRoot == null) {            overallRoot = new TreeNode<>(addThis);        } else {            add(overallRoot, addThis);        }    }    private TreeNode<E> add(TreeNode<E> node, E addThis) {        if...

  • i need help to modify this Tree class to include a method leavesCount that returns the...

    i need help to modify this Tree class to include a method leavesCount that returns the number of leaves in a binary tree. (NOTE: Complete leavesCount and leavesCountHelper methods in the Tree class). I already have the test class. java class TreeNode< T extends Comparable< T > > { TreeNode< T > leftNode; T data; TreeNode< T > rightNode; public TreeNode( T nodeData ) { data = nodeData; leftNode = rightNode = null; } public void insert( T insertValue )...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • JAVA- Complete the code by following guidelines in comments. class CircularList { private Link current; private...

    JAVA- Complete the code by following guidelines in comments. class CircularList { private Link current; private Link prev; public CircularList() { // implement: set both current and prev to null } public boolean isEmpty() { // implement return true; } public void insert(int id) { // implement: insert the new node behind the current node } public Link delete() { // implement: delete the node referred by current return null; } public Link delete(int id) { // implement: delete the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT