see below questions and provide me adjusted coding by using my coding. I share my coding and test failure message at the end. 1. BST.java
1. BST.java
2.BSTNode.java
Binary Search Tree
 you will be coding the add() and remove() methods of abinary search tree. A binary search tree, or BST, is a collection of nodes, each having a data item and a reference pointing to a left and a right child node. The BST must adhere to the following order property: for any given node, its left child's data and all of its children's data must be less than the current node while its right child's data and all of its children's data must be greater than the current node. In order to compare the data, all elements added to the tree must implement Java's generic Comparable interface. Since trees are naturally recursive structures, each of these methods should be implemented recursively.
IMPORTANT:
- You will be given unlimited attempts on this assignment, with no cooldown between submissions.
- Please run your code before each submission to ensure that there are no formatting errors! If there are formatting errors in your code, your code will not be graded and a submission attempt will be logged. For more information, please review the Vocareum overview below.
BSTNode
A BSTNode class is provided to you and will be used to represent the nodes in the tree. This file should be treated as read-only and should not be modified in any way. This BSTNode class contains getter and setter methods to access and mutate the structure of the nodes. Please make sure that you understand how this class works, as interaction with this class is crucial for this assignment.
Pointer Reinforcement
Since both the add() and remove() methods may change the structure of the tree, we highly recommend that you use a technique called pointer reinforcement. Although using pointer reinforcement is not required, it will help to make your code cleaner, and it'll also help greatly in future assignments if you end up taking the next course in our series! Below is a video created by our 1332 TAs, timestamped to a section on pointer reinforcement.
Pointer Reinforcement Overview
Comparable
As stated, the data in the BST must implement the Comparable interface. As you'll see in the les, the generic typing has been specified to require that it implements the Comparable interface. You use the interface by making a method call like data1.compareTo(data2). This will return an int, and the value tells you how data1 and data2 are in relation to each other.
- If the int is positive, then data1 is larger than data2.
- If the int is negative, then data1 is smaller than data2.
- If the int is zero, then data1 equals data2.
Note that the returned value can be any integer in Java's int range, not just -1, 0, 1.
Successor
Recall that earlier in the modules you learned about the successor and predecessor of a node in a tree. As a refresher, the successor of a node, n, is the node in the tree that contains the smallest data that is larger than n's data. The predecessor of a node, n, is the node in the tree that contains the largest data that is smaller than n's data. When removing a node from a BST that has two children, we can choose to replace the removed node with either it's successor or predecessor. For the 2-child case in remove(), you will be replacing the removed node with its successor node, NOT the predecessor node. For more details, please refer to the javadocs for remove().
Helper Methods
You'll also notice that the public method stubs we've provided do not contain the parameters necessary for recursion to work, so these public methods should act as "wrapper methods" for you to use. You will have to write private recursive helper methods and call them in these wrapper methods. All of these helper methods must be private. To reiterate, do not change the method headers for the provided methods.
General Tips
Don't forget your base case; this should be the first thing that is checked in your recursive calls. Note that the base case for add() may be different that the base case in remove().
If you get stuck on remove(), the video above on pointer reinforcement has pseudocode for the remove() method!
- We highly recommend copying the starter code and working in your preferred IDE in order to have access to features such as code completion, auto-formatting, and much more!
Here are general assignment guidelines that should be followed.
- Do not include any package declarations in your classes.
- Do not change any existing class headers, constructors, instance/global variables, or method signatures. For example, do not add throws to the method headers since they are not necessary. Instead, exceptions should be thrown as follows: throw new InsertExceptionHere("Error: some exception was thrown");
- All helper methods you choose to write should be made private. Recall the idea of Encapsulation in Object-Oriented Programming!
- Do not use anything that would trivialize the assignment. (e.g. Don't import/use java.util.ArrayList for an ArrayList assignment.)
- Always be very conscious of efficiency. Even if your method is to be , traversing the structure multiple times is considered inefficient unless that is absolutely required (and that case is extremely rare).
- If applicable, use the generic type of the class; do not use the raw type of the class. For example, use new LinkedList() instead of new LinkedList().
Use of the following statements should be avoided at all times.
package | System.arraycopy() | clone() |
assert() | Arrays class | Array class |
Thread class | Collections class | Collection.toArray() |
Reflection APIs | Inner or nested classes | Lambda Expressions |
The Vocareum (code editor) interface has six main components:
- The Drop-Down in the top left. This lets you choose from multiple available files. Note that this drop-down will only be visible in assignments that require multiple files.
- The Run button. This will compile your code and run a file scan. Running your code will not count towards your total allowed submission attempts, therefore you are free to run as many times as needed.
- The Submit button. This will compile your code, run a file scan, grade your assignment, and output results to console. Note that for most assignments in this class, you will only be allowed a limited number of submissions. A submission is counted when the submit button is clicked, regardless of whether or not your code can compile or if there are any file issues. Therefore, we highly recommend that you run your code before submitting to ensure that there are no issues that will prevent your code from being graded and that every submission attempt will generate meaningful results.
- The Reset button. This will revert all your changes and reset your code to the default code template.
- The Code Window. This is where you will writeyour code. For large coding assignments, we highly recommend copying the starter code and working in your preferred IDE to have access to features such as code completion, auto-formatting, and much more!
- The Output Window. This window will appear whenever you run or submit your code and will display the output for you to view.
My Coding :
1.BST.java
import java.util.Collection;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/**
* Your implementation of a binary search tree.
*
*/
public class BST> {
// DO NOT ADD OR MODIFY INSTANCE VARIABLES.
private BSTNode root;
private int size;
/**
* A no-argument constructor that should initialize an empty BST.
*
* Since instance variables are initialized to their default values, there
* is no need to doanything for this constructor.
*/
public BST() {
// DO NOT IMPLEMENT THIS CONSTRUCTOR!
}
/**
* Initializes the BST with the data in the Collection. The data
* should be added in the same order it is in the Collection.
*
* Hint: Not all Collections are indexable like Lists, so a regular for loop
* will not work here. However, all Collections are Iterable, so what type
* of loop would work?
*
* @param data the data to add to the tree
* @throws IllegalArgumentException if data or any element in data is null
*/
/**
* Add the data as a leaf in the BST. Should traverse the tree to find the
* appropriate location. If the data is already in the tree, then nothing
* should be done (the duplicate shouldn't get added, and size should not be
* incremented).
*
* Should have a running time of O(log n) for a balanced tree, and a worst
* case of O(n).
*
* @throws IllegalArgumentException if the data is null
* @param data the data to be added
*/
public void add(T data) {
if (data == null) {
throw new IllegalArgumentException(
"Data is null and cannot be added.");
} else if (root == null) {
//make new root from the singular piece of data
root = new BSTNode<>(data);
size++;
} else {
//call recursive helper method
rAdd(data, root);
}
}
/**
* recursive helper method for Add. checks where to add the data,
* and adds it in to the tree.
*
* @param data the data to be added
* @param node the node where we start our search for where to add
*/
private void rAdd(T data, BSTNode node) {
//do normally
//if the data is > than other data
//if data is less than other data
//use nested conditionals
if (node.getData().compareTo(data) > 0) {
//aka, if the first thing aka root is greater
//then we add to the left
//check to see if there's anything to the left
if (node.getLeft() == null) {
//add data
BSTNode newNode = new BSTNode(data);
node.setLeft(newNode);
size++;
} else {
//call method to repeat process
rAdd(data, node.getLeft());
}
} else if (node.getData().compareTo(data) < 0) {
//then we add to the right
if (node.getRight() == null) {
BSTNode newNode = new BSTNode(data);
node.setRight(newNode);
size++;
} else {
rAdd(data, node.getRight());
}
}
}
/**
* Removes the data from the tree. There are 3 cases to consider:
*
* 1: the data is a leaf (no children). In this case, simply remove it.
* 2: the data has one child. In this case, simply replace it with its
* child.
* 3: the data has 2 children. Use the predecessor to replace the data.
* You MUST use recursion to find and remove the predecessor (you will
* likely need an additional helper method to handle this case efficiently).
*
* Should have a running time of O(log n) for a balanced tree, and a worst
* case of O(n).
*
* @throws IllegalArgumentException if the data is null
* @throws java.util.NoSuchElementException if the data is not found
* @param data the data to remove from the tree.
* @return the data removed from the tree. Do not return the same data
* that was passed in. Return the data that was stored in the tree.
*/
public T remove(T data) {
//exception data is null
if (data == null) {
throw new IllegalArgumentException(
"Data is null and cannot be added to the tree.");
} else if (root == null) {
//exception if data not found
throw new NoSuchElementException(
"Root is null, therefore no data can be removed.");
}
//null b/c there's nothing in front of the root and this is the
//first recursive call
T removed = rRemove(data, null, root);
if (removed == null) {
throw new NoSuchElementException(
"Removed a null value. Something went wrong.");
}
size--;
return removed;
}
/**
* recursive helper method for remove. checks where to remove the data,
* and removes it from the tree.
*
* @param data the data to be added
* @param parent the previous node
* @param current the current node
* @return the data that was removed
*/
private T rRemove(T data, BSTNode parent, BSTNode current) {
if (current == null) {
return null;
}
if (data.equals(current.getData())) {
//this is the node we want to remove
//save the old data
T oldData = current.getData();
if (current.getLeft() == null && current.getRight() == null) {
//node is a leaf
if (parent == null) {
root = null;
current = root;
} else if (parent.getLeft() != null
&& parent.getLeft().equals(current)) {
parent.setLeft(null);
current = parent.getLeft();
} else if (parent.getRight() != null
&& parent.getRight().equals(current)) {
parent.setRight(null);
current = parent.getRight();
}
} else if (current.getLeft() != null
&& current.getRight() == null) {
//has a single child
current = current.getLeft();
} else if (current.getRight() != null
&& current.getLeft() == null) {
current = current.getRight();
} else {
//do something
//has two children
current.setData(previous(current, current.getLeft()));
}
if (parent != null) {
if (parent != null && current == parent.getLeft()) {
//if parent is the leftmost node
parent.setLeft(current);
} else {
parent.setRight(current);
}
} else {
root = current;
}
return oldData;
} else if (current.getData().compareTo(data) < 0) {
return rRemove(data, current, current.getRight());
} else {
return rRemove(data, current, current.getLeft());
}
}
/**
* recursive method to find the previous node
*
* @param parent where we start our search
* @param current the node where we end our search
* @return the data in the previous node
*/
private T previous(BSTNode parent, BSTNode current) {
if (current.getRight() != null) {
//call method again bc we want to find where it has no babies
return previous(current, current.getRight());
} else {
if (parent.getLeft() == current) {
//we r @ leftmost node of parent
parent.setLeft(current.getLeft());
} else if (parent.getRight() == current) {
// we r @ rightmost node of parent
//set to left bc the left one is smaller
parent.setRight(current.getLeft());
}
}
return current.getData();
}
/**
* Returns the data in the tree matching the parameter passed in (think
* carefully: should you use value equality or reference equality?).
*
* Should have a running time of O(log n) for a balanced tree, and a worst
* case of O(n).
*
* @throws IllegalArgumentException if the data is null
* @throws java.util.NoSuchElementException if the data is not found
* @param data the data to search for in the tree.
* @return the data in the tree equal to the parameter. Do not return the
* same data that was passed in. Return the data that was stored in the
* tree.
*/
private T get(T data) {
if (data == null) {
throw new IllegalArgumentException(
"Data is null and cannot be searched for. "
+ "Enter data that is not null.");
}
return rGet(data, root);
}
/**
* recursive helper method for get. Checks where the data is, and
* returns that data
*
* @param data the data to be found
* @param current the node where we start our search for the data
* @return the data in the tree equal to the parameter
*/
private T rGet(T data, BSTNode current) {
if (current == null) {
throw new NoSuchElementException(
"Current node is null, data not found in tree.");
} else if (current.getData().equals(data)) {
//base case
return current.getData();
} else if (current.getData().compareTo(data) < 0) {
return rGet(data, current.getRight());
} else if (current.getData().compareTo(data) > 0) {
return rGet(data, current.getLeft());
}
return null;
}
/**
* Returns whether or not data equivalent to the given parameter is
* contained within the tree. The same type of equality should be used as
* in the get method.
*
* Should have a running time of O(log n) for a balanced tree, and a worst
* case of O(n).
*
* @throws IllegalArgumentException if the data is null
* @param data the data to search for in the tree.
* @return whether or not the parameter is contained within the tree.
*/
private boolean contains(T data) {
if (data == null) {
throw new IllegalArgumentException(
"Data is null, and cannot be searched for.");
}
return rContains(data, root);
}
/**
* recursive helper method for contains. Checks to see if the tree
* contains the given data.
*
* @param data the data to be checked
* @param current the node where we start our search for the data
* @return a boolean for if the tree is a bst
*/
private boolean rContains(T data, BSTNode current) {
if (current == null) {
return false;
} else if (current.getData().equals(data)) {
return true;
} else if (current.getData().compareTo(data) < 0) {
return rContains(data, current.getRight());
} else if (current.getData().compareTo(data) > 0) {
return rContains(data, current.getLeft());
} else {
return false;
}
}
/**
* Should run in O(n).
*
* @return a preorder traversal of the tree
*/
private List preorder() {
List poList = new ArrayList<>();
return rPreorder(poList, root);
}
/**
* recursive helper method for preorder
*
* @param aList the list of values
* @param current the node we're looking at
* @return a preorder traversal of the tree
*/
private List rPreorder(List aList, BSTNode current) {
if (current != null) {
aList.add(current.getData());
rPreorder(aList, current.getLeft());
rPreorder(aList, current.getRight());
}
return aList;
}
/**
* Should run in O(n).
*
* @return an inorder traversal of the tree
*/
private List inorder() {
List inoList = new ArrayList<>();
return rInorder(inoList, root);
}
/**
* recursive helper method for inorder
*
* @param aList the list of values
* @param current the node we're looking at
* @return an inorder traversal of the tree
*/
private List rInorder(List aList, BSTNode current) {
if (current != null) {
//call all the left ones first bc theyre smallest
rInorder(aList, current.getLeft());
//add it to the list
aList.add(current.getData());
//THEN call all the right ones
rInorder(aList, current.getRight());
}
return aList;
}
/**
* Should run in O(n).
*
* @return a postorder traversal of the tree
*/
private List postorder() {
List poList = new ArrayList<>();
return rPostorder(poList, root);
}
/**
* recursive helper method for postorder
*
* @param aList the list of values
* @param current the node we're looking at
* @return a postorder traversal of the tree
*/
private List rPostorder(List aList, BSTNode current) {
if (current != null) {
rPostorder(aList, current.getLeft());
rPostorder(aList, current.getRight());
aList.add(current.getData());
}
return aList;
}
/**
* Generate a level-order traversal of the tree.
*
* To dothis, add the root node to a queue. Then, while the queue isn't
* empty, remove one node, add its data to the list being returned, and add
* its left and right child nodes to the queue. If what you just removed is
* {@code null}, ignore it and continue with the rest of the nodes.
*
* Should run in O(n). This does not need to be done recursively.
*
* @return a level order traversal of the tree
*/
private List levelorder() {
List loList = new ArrayList<>();
Queue> loQueue = new LinkedList<>();
return rLevelorder(loList, loQueue, root);
}
/**
* helper method for levelorder
*
* @param aList the list of values
* @param aQueue the elements from tree to be placed in list
* @param current the node we're looking at
* @return a preorder traversal of the tree
*/
private List rLevelorder(
List aList, Queue> aQueue, BSTNode current) {
if (current != null) {
aQueue.add(current);
while (!aQueue.isEmpty()) {
current = aQueue.remove();
aList.add(current.getData());
if (current.getLeft() != null) {
aQueue.add(current.getLeft());
}
if (current.getRight() != null) {
aQueue.add(current.getRight());
}
}
}
return aList;
}
/**
* This method checks whether a binary tree meets the criteria for being
* a binary search tree.
*
* This method is a static method that takes in a BSTNode called
* {@code treeRoot}, which is the root of the tree that you should check.
*
* You may assume that the tree passed in is a proper binary tree; that is,
* there are no loops in the tree, the parent-child relationship is
* correct, that there are no duplicates, and that every parent has at
* most 2 children. So, what you will have to check is that the order
* property of a BST is still satisfied.
*
* Should run in O(n). However, you should stop the check as soon as you
* find evidence that the tree is not a BST rather than checking the rest
* of the tree.
*
* @param the generic typing
* @param treeRoot the root of the binary tree to check
* @return true if the binary tree is a BST, false otherwise
*/
private static > boolean isBST(
BSTNode treeRoot) {
return rIsBST(treeRoot, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
/**
* recursive helper method for isBST; checks to see if
* the tree is a BST
*
* @param current the node we're looking at
* @param min the minimum value the data can be
* @param max the maximum value the data can be
* @return a boolean for if the tree is a BST
*/
private static boolean rIsBST(BSTNode current, int min, int max) {
if (current == null) {
return true;
}
if (current.getData().compareTo(min) < 0) {
return false;
} else if (current.getData().compareTo(max) > 0) {
return false;
}
return rIsBST(current.getLeft(), min,
(Integer) current.getData() - 1)
&& rIsBST(current.getRight(),
(Integer) current.getData() + 1, max);
}
/**
* Clears the tree.
*
* Should run in O(1).
*/
private void clear() {
root = null;
size = 0;
}
/**
* Calculate and return the height of the root of the tree. A node's
* height is defined as {@code max(left.height, right.height) + 1}. A leaf
* node has a height of 0 and a null child should be -1.
*
* Should be calculated in O(n).
*
* @return the height of the root of the tree, -1 if the tree is empty
*/
private int height() {
if (root == null) {
return -1;
}
return rHeight(root);
}
/**
* recursive helper method for height
*
* @param current the node we're looking at
* @return an integer with the height of the tree
*/
private int rHeight(BSTNode current) {
if (current == null) {
return -1;
} else if (current.getLeft() == null && current.getRight() == null) {
//no children we dont count these
return 0;
} else {
return Math.max(rHeight(current.getLeft()),
rHeight(current.getRight())) + 1;
}
}
/**
* Returns the size of the BST.
*
* For grading purposes only. You shouldn't need to use this method since
* you have direct access to the variable.
*
* @return the number of elements in the tree
*/
public int size() {
// DO NOT MODIFY THIS METHOD!
return size;
}
/**
* Returns the root of the BST.
*
* For grading purposes only. You shouldn't need to use this method since
* you have direct access to the variable.
*
* @return the root of the tree
*/
public BSTNode getRoot() {
// DO NOT MODIFY THIS METHOD!
return root;
}
}
2.BSTNode.java
/**
* Node class used for implementing the BST.
*
* DO NOT MODIFY THIS FILE!!
*
* @author CS 1332 TAs
* @version 1.0
*/
public class BSTNode> {
private T data;
private BSTNode left;
private BSTNode right;
/**
* Constructs a BSTNode with the given data.
*
* @param data the data stored in the new node
*/
BSTNode(T data) {
this.data = data;
}
/**
* Gets the data.
*
* @return the data
*/
T getData() {
return data;
}
/**
* Gets the left child.
*
* @return the left child
*/
BSTNode getLeft() {
return left;
}
/**
* Gets the right child.
*
* @return the right child
*/
BSTNode getRight() {
return right;
}
/**
* Sets the data.
*
* @param data the new data
*/
void setData(T data) {
this.data = data;
}
/**
* Sets the left child.
*
* @param left the new left child
*/
void setLeft(BSTNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right the new right child
*/
void setRight(BSTNode right) {
this.right = right;
}
}
**Please solve below Test Failure message . Please adjust my coding and give me a chance to get the perfect score.
Step by Step Solution
3.47 Rating (147 Votes )
There are 3 Steps involved in it
Step: 1
Certainly I will regenerate the code for you with the necessary adjustments based on the provided instructions Here is the revised code for BSTjava java import javautilNoSuchElementException import ja...See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started