0

I have a binary search tree which stores objects. For inserting objects to it I am using Int value as a key. I get that value by calling method form the object like this:

public class Tree
{
    // The root node of the tree which is null;
    private Node root;
    private double largest;

    private Node insert (Node tree, Element d)
    {
        if (tree == null)  return new Node(d);
        else if (d.getPlaceInTable() < tree.data.getPlaceInTable()) tree.left = insert (tree.left, d);
        else if (d.getPlaceInTable() > tree.data.getPlaceInTable()) tree.right = insert (tree.right, d);

    return tree;

    }

    public void insert (Element d)
    {
    root = insert (root, d);
    }

But what if I want to use Elements name as a key value which is string? How can I do it? Should I use compareTo() method? I know how to compare string1.compareTo(string2) but I really don' have any idea how I can use it in this case. If you have any suggestions, I really appreciate that.

2
  • yes, String implements Comparable, so you can do d.getName().compareTo(tree.data.getName()) > 0 Commented Dec 11, 2012 at 15:38
  • thank you for your help, it worked just as I supposed. Commented Dec 11, 2012 at 15:45

1 Answer 1

1

Yes, String implements Comparable, so you can do

d.getName().compareTo(tree.data.getName()) < 0 for the left node and d.getName().compareTo(tree.data.getName()) >= 0 for the right node

Also note, that in your original code you do not insert anything in your tree when values are equal.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I know that, I am ignoring equal values, because I am storing elements from periodic table, which are not equal to each other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.