Java- CompareTo with Binary Search Tree

Click For Summary

Discussion Overview

The discussion revolves around implementing a method to check if a given String name exists among Dog objects in a binary search tree (BST) in Java. The focus is on the challenges faced in the containsRecursive() method and how to effectively compare names within the structure of the tree.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant describes difficulties in using the compareTo() method within the Node class to compare Dog names in the containsRecursive() method.
  • Another participant points out that the binary tree is structured to order by weight rather than name, suggesting that searching by name would require examining each node.
  • A proposed alternative containsRecursive() method is shared, which uses name comparison directly and includes case insensitivity.
  • One participant expresses gratitude for the assistance received in the discussion.
  • Another participant mentions their upcoming need to tackle Java, indicating a potential interest in the topic.

Areas of Agreement / Disagreement

Participants do not reach a consensus on the best approach to implement the name comparison in the binary search tree, as the original poster's method and the suggested alternative both reflect different strategies for handling the search.

Contextual Notes

The discussion highlights the limitation of the current binary search tree structure, which is organized by weight, complicating name-based searches. There is also an indication of unresolved assumptions regarding the design choices for the tree.

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