Java- CompareTo with Binary Search Tree

In summary, the conversation was about a problem with implementing a binary search tree to compare a given string name with the names of Dog objects. The issue was with the containsRecursive() method and the attempted solutions of creating a compareTo() method in the inner Node class and a compareByName() method in the Dog class. However, the problem was that the tree was ordered by weight, not by name, so the only solution was to examine each node individually. A corrected method was provided for this purpose.
  • #1
Smiles1
8
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
  • #2
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);
   }
 
  • #3
THANK YOU! Thank you for the help. :-)
 
  • #4
Hmm...Java is probably going to be what I have to tackle next, unfortunately...thanks here for help)
 

FAQ: Java- CompareTo with Binary Search Tree

What is the purpose of using CompareTo with Binary Search Tree in Java?

The CompareTo method in Java is used to compare two objects and determine their ordering. In the context of Binary Search Trees, it is used to compare the value of a node with the value of another node to determine if it should be placed on the left or right side of the tree.

How does CompareTo work in Binary Search Trees?

The CompareTo method in Binary Search Trees compares the value of a node with the value of another node and returns a negative value if the first value is less than the second, a positive value if the first value is greater than the second, and 0 if they are equal. This allows for efficient insertion, retrieval, and removal of nodes in the tree based on their values.

Can CompareTo be used to compare non-primitive data types in Binary Search Trees?

Yes, CompareTo can be used to compare non-primitive data types in Binary Search Trees as long as the objects being compared implement the Comparable interface. This interface provides a compareTo method that can be used for comparison.

What is the time complexity of CompareTo in Binary Search Trees?

The time complexity of CompareTo in Binary Search Trees is O(log n), where n is the number of nodes in the tree. This is because Binary Search Trees are structured in a way that allows for efficient comparison and traversal, resulting in a logarithmic time complexity.

How does CompareTo help with maintaining the order of nodes in Binary Search Trees?

CompareTo helps with maintaining the order of nodes in Binary Search Trees by comparing the values of nodes and ensuring that they are placed in the correct position based on their value. This allows for efficient searching, sorting, and insertion of nodes in the tree.

Similar threads

Back
Top