Please help me implement the two search functions in BinarySearchTree.java publi
ID: 3707520 • Letter: P
Question
Please help me implement the two search functions in BinarySearchTree.java
public class BinarySearchTree<E extends Comparable<E>>
{
TreeNode<E> root;
/**
* Insert given node to this binary search tree. If this tree
* is empty, the given node becomes the root of this tree.
* @param newNode the given node to be inserted
*/
public void insert(TreeNode<E> newNode){
}
/**
* Insert given data to this binary search tree. If this tree
* is empty, the given node becomes the root of this tree.
* @param data the given data to be inserted
*/
public void insert(E data){
}
}
Explanation / Answer
public class BinarySearchTree<E extends Comparable<E>>
{
TreeNode<E> root;
private Comparator<T> comparator;
/**
* Insert given node to this binary search tree. If this tree
* is empty, the given node becomes the root of this tree.
* @param newNode the given node to be inserted
*/
public void insert(TreeNode<E> newNode)
{
this.root = insert_util( this.root , newNode.getData() );
}
private int compare(T x, T y)
{
if(comparator == null)
return x.compareTo(y);
return comparator.compare(x,y);
}
/**
* Insert given data to this binary search tree. If this tree
* is empty, the given node becomes the root of this tree.
* @param data the given data to be inserted
*/
public void insert(E data)
{
this.root = insert_util( this.root , data );
}
private TreeNode<E> insert_util(TreeNode<E> node, E data)
{
// if tree is empty
if (node == null)
// create a new node
node = new TreeNode<E>(data);
// if the dats lies in the right subtree
else if (compare(node.getData(), data) < 0)
node.setRight(insert_util(node.getRight(), data));
// if the dats lies in the left subtree
else
node.setLeft(insert_util(node.getLeft(), data));
return node;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.