Java- CompareTo with Binary Search Tree

Click For Summary
SUMMARY

The forum discussion centers on implementing a method to search for a Dog object by name within a Binary Search Tree (BST) in Java. The user initially attempted to use a custom compareTo() method in the Node class and a compareByName() method in the Dog class, but faced issues with the containsRecursive() method always returning false. The solution provided involves modifying the containsRecursive() method to search through the tree without relying on the tree's structure, which is based on weight rather than name.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with Binary Search Trees (BST)
  • Knowledge of method overriding in Java
  • Experience with string comparison in Java
NEXT STEPS
  • Implement and test the corrected containsRecursive() method for searching by name
  • Explore Java's compareToIgnoreCase() method for case-insensitive comparisons
  • Learn about tree traversal techniques in Java, such as in-order and pre-order traversal
  • Investigate the implications of using different properties (like weight vs. name) for BST structure
USEFUL FOR

Java developers, computer science students, and anyone interested in data structures and algorithms, particularly those working with Binary Search Trees and object comparison in Java.

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)
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
1K
Replies
1
Views
2K
Replies
3
Views
1K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K