0

I want to make a generic BST, that can be made up of any data type, but i'm not sure how I could add things to the tree, if my BST is generic. All of my needed code is below. I want my BST made up of Locations, and sorted by the x variable. Any help is appreciated.

Major thanks for looking.

public void add(E element)
{
    if (root == null)
         root = element;
    if (element < root)
         add(element, root.leftChild);
    if (element > root)
         add(element, root.rightChild);
    else
         System.out.println("Element Already Exists");
}

private void add(E element, E currLoc)
{
    if (currLoc == null)
         currLoc = element;
    if (element < root)
         add(element, currLoc.leftChild);
    if (element > root)
         add(element, currLoc.rightChild);
    else
         System.out.println("Element Already Exists);
}

Other Code

public class BinaryNode<E>
{
    E BinaryNode;
    BinaryNode nextBinaryNode;
    BinaryNode prevBinaryNode;

    public BinaryNode()
    {
        BinaryNode = null;
        nextBinaryNode = null;
        prevBinaryNode = null;
    }

}


public class Location<AnyType> extends BinaryNode
{
    String name;
    int x,y;

    public Location()
    {
        name = null;
        x = 0;
        y = 0;
    }

    public Location(String newName, int xCord, int yCord)
    {
        name = newName;
        x = xCord;
        y = yCord;
    }

    public int equals(Location otherScene)
    {
        return name.compareToIgnoreCase(otherScene.name);
    }


}
2
  • This sounds like homework to me. Commented Apr 4, 2010 at 17:48
  • 2
    How about this(java.util.Collections.binarySearch(List<? extends Comparable<? super T>>, T)) for inspiration? Commented Apr 4, 2010 at 17:49

1 Answer 1

6

You can constrain your type to implement Comparable<? super E>:

public class BinarySearchTree<E extends Comparable<? super E>>

Then you can call compareTo:

// Instead of if (element < root)
if (element.compareTo(root) < 0)

(etc)

Alternatively, you could force the caller to pass in a Comparator<E> when the search tree is constructed, and then use that to compare elements. That's actually a more flexible solution in my view - it means you could create different binary search trees for the same element type, but ordering them in different ways.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.