4. Write the Java code for a method of the BinarySearchTree class -Comparable sm
ID: 3693060 • Letter: 4
Question
4. Write the Java code for a method of the BinarySearchTree class -Comparable smallest() that returns the smallest element of a tree. Add comments to the code explaining the steps. 4. Write the Java code for a method of the BinarySearchTree class -Comparable smallest() that returns the smallest element of a tree. Add comments to the code explaining the steps. 4. Write the Java code for a method of the BinarySearchTree class -Comparable smallest() that returns the smallest element of a tree. Add comments to the code explaining the steps.Explanation / Answer
the following is method for finding smallest element in bst as
comparable smallest()
{
//assigning root node to t for temporary moves
node<T> t=root;
//check whether the tree is empty or not
if(t==null)
System.out.println("tree is empty");
//moves towards left side to reach leaf nodes with havin left childen
while(t.left!=null)
{
t=t.left;
}
//at the end of while loop we are in leaf level or one level upper than leaf level wlth only one rigth child
//that was the smallest element in tree why because based on bst property left child is less than root and rigth child
return t.data;//returns the smallest in tree
}
where the node<T> is a class for node declaration at each time.the code for node class is as follows
private class Node<T>
{
private T data;
private Node<T> left, right;
public Node(T data, Node<T> l, Node<T> r)
{
left = l; right = r;
this.data = data;
}
public Node(T data)
{
this(data, null, null);
}
public String toString()
{
return data.toString();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.