Java Java- CompareTo with Binary Search Tree

AI Thread Summary
The discussion centers on implementing a method to check if a given String name exists within a Binary Search Tree (BST) of Dog objects. The user is struggling with the containsRecursive() method, which is currently set up to compare Dog objects based on weight rather than name. A suggested solution involves modifying the containsRecursive() method to compare names directly, using String comparison instead of relying on the tree's weight-based structure. This adjustment allows for a more accurate search for Dog names within the BST. The conversation highlights the importance of aligning the search criteria with the structure of the data being used.
Smiles1
Messages
7
Reaction score
0
I am having a hard time implementing comparing a given String name with the names of the Dog objects in my binary Search Tree.

The problem comes from my containsRecursive() method. I need to use a String name to find if the name is already in my Binary Search Tree.Here's what I've tried:

Creating my own compareTo() method in my inner Node class

Code:
public int compareTo(Dog t) {
            int comparisonVal = this.data.getName().compareTo(t.getName());
            if (this.data.getName().compareTo(t.getName()) == 0) {
                return 0;
            } else if (this.data.getName().compareTo(t.getName()) < 0) {
                return -1;
            } else {
                return 1;
            }

        }

I've also tried creating a compareByName() method in my dog class.

Code:
public int compareByName(Dog otherDog) {
        return name.compareTo(otherDog.name);
    }
Neither of these are working as I tried accessing them within my containsRecursive() and the program always returns false when it should return true because the name matches.. I understand the overall formula for creating a compareTo() but I'm not sure how to make it fit in my program.

Here is my App Class:

Code:
public class App {

    public static void main(String[] args) {
        BSTree dogOTree = new BSTree();

        dogOTree.addDog("Jackson", 65.28);
        dogOTree.addDog("Tick", 69.88);
        dogOTree.addDog("Nia", 75.44);
        //Layla is my dog! She was named after the Eric Clapton song.
        dogOTree.addDog("Layla", 32.02);
        dogOTree.addDog("Bagel", 21.06);
        dogOTree.addDog("Milo", 24.73);
        
//        Dog dog1 = new Dog("BaconEater", 44.88);
        
        dogOTree.displayInOrder();
        System.out.println(dogOTree.containsDog("Layla"));
    }

}
Here is my BSTree Class:

Code:
public class BSTree{
        

    class Node {

        Dog data;
        Node leftChild;
        Node rightChild;
        
        
        Node(Dog data) {
            this.data = data;
            this.leftChild = null;
            this.rightChild = null;
        }
        
        public int compareTo(Dog t) {
            int comparisonVal = this.data.getName().compareTo(t.getName());
            if (this.data.getName().compareTo(t.getName()) == 0) {
                return 0;
            } else if (this.data.getName().compareTo(t.getName()) < 0) {
                return -1;
            } else {
                return 1;
            }

        }
       
    }

    private Node root;
  
    
    public BSTree() {
        root = null;
   
    }

    public boolean add(Dog data) {
        root = addRecursive(root, data);
        return true;
    }

    private Node addRecursive(Node current, Dog data) {
        if (current == null) { // If it's root
            return new Node(data);
        } else if (data.getWeight() < current.data.getWeight()) { //navigate left
            //Vrrooom vrroom go left
            current.leftChild = addRecursive(current.leftChild, data);
            return current;
        } else if (data.getWeight() > current.data.getWeight()) {
            current.rightChild = addRecursive(current.rightChild, data);
            return current;
        } else {
            return current;
        }
    }

    public boolean containsDog(String name) {
        return containsRecursive(root, name);
        //Start at the root and looks for data
    }
    // The problem is here!
    private boolean containsRecursive(Node current, String name) {
        Dog tempDog = new Dog(name, 0.0);
        if (current == null) {
            return false;
        }
        if (tempDog.getName().compareTo(current.data.getName()) == 0) {
            return true;
        } else if (tempDog.getName().compareTo(current.data.getName()) < 0) { //Go left!
            return containsRecursive(current.leftChild, name);
        } else {
            return containsRecursive(current.rightChild, name);
        }

    }

    /*
    While node is not null 
    recursively traverse left child
    Display node's value
    recursively traverse right child
     */
    public void displayInOrder() {
        inOrderTraversal(root);
    }

    private void inOrderTraversal(Node node) {
        if (node != null) {
            inOrderTraversal(node.leftChild);
            System.out.println(" " + node.data);
            inOrderTraversal(node.rightChild);
        }
    }
    //Adds a Dog object to the tree.  Returns true on success or false on failure (if Dog with that name already exists).
      public boolean addDog(String name, double weight){ 
          return this.add(new Dog(name, weight));
      } 
//     public double getDogWeight(String name){
//         //Returns the weight of the dog with the specified name if it exists in the tree, or returns -1 otherwise.
//         //return
}
Annndd here is my Dog class.

Code:
public class Dog {
    private String name;
    private double weight;

    public Dog(String name, double weight) {
        this.name = name;
        this.weight = weight;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Dog {" + " name= " + name + ", weight= " + weight;
    }

    public int compareByName(Dog otherDog) {
        return name.compareTo(otherDog.name);
    }

    
}

Any help is greatly appreciated! With a thank you in advance.
 
Technology news on Phys.org
Your problem is that the order in your binary tree is by weight, not by name. So to search by name, there's really no alternative except to examine each node. Here's a corrected method:

Code:
   private boolean containsRecursive(Node current, String name) {
      if (current == null) {
         return false;
      }
      if (name.compareToIgnoreCase(current.data.getName()) == 0) {
         return (true);
      }
      boolean inLeft = containsRecursive(current.leftChild, name);
      if (!inLeft) {
         return (containsRecursive(current.rightChild, name));
      }
      return (true);
   }
 
THANK YOU! Thank you for the help. :-)
 
Hmm...Java is probably going to be what I have to tackle next, unfortunately...thanks here for help)
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...
Back
Top