Question: Please change the BST.java as followed: In the case in which the deleted node has two children, write the code in two ways. a) always
Please change the BST.java as followed: 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 experiment 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.java:
public class BST
public BST() { this.root = null; }
public void insert(T datum) throws BSTException { this.root = insert(this.root, datum); }
private Node
public T lookup(T target) { Node
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
//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
public int getDepth() { return getDepth(root); }
public int getDepth(Node
public String toString() { String retval = ""; return toString(root, retval); }
public String toString(Node
public static void main(String args[]) throws BSTException { BST
Node.java:
public class Node
public Node(T data, Node
public Node(T data) { this(data, null, null); }
public T getData() { return this.data; }
public Node
public Node
public void setRight(Node
public void setDepth(int d) { this.depth = d; }
public int getDepth() { return this.depth; } }
BSTException.java:
public class BSTException extends Exception { public BSTException() { super("BST Exception"); }
public BSTException(String s) { super(s); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
