Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the method int count(E low, E high) for the binary search tree present

ID: 3861674 • Letter: I

Question

Implement the method int count(E low, E high) for the binary search tree presented in class. The method returns the number of elements in the tree that are greater than or equal to low and smaller than or equal to high. bullet The elements stored in a binary search tree implement the interface Comparable. Recall that the method int compareTo(E other) returns a negative integer, zero, or a positive integer as the instance is less than, equal to, or greater than the specified object. bullet A method that is visiting too many nodes will get a maximum of 9 marks. bullet Given a binary search tree, t, containing the values 1, 2, 3, 4, 5, 6, 7, 8, the call t.count(3, 6) returns the value 4. public class BinarySearchTree {private static class Node {private T value; private Node left; private Node right; private Node(T value) {this. value = value; left = null; right = null;}} private Node root = null; public int count (E low, E high) {

Explanation / Answer

public int count(E low,E high)
{
   Node<E> r = root;
   int c;
   c = find_count(r,low,high);
   return c;
}
public int find_count(Node<E> r,E low,E high)
{

   static int c=0;
   if(r.compareTo(low)>=0 && r.compareTo(high)<=0)c++;
   if(r.left!=null)find_count(r.left,low,high);
   if(r.right!=null)find_count(r.right,low,high);
   return c;  
}