Search Tree

Hi I have a binary search tree which i want to insert any kind of object in to, so i have methods:

insert(Object o)

remove(Object o)

....

but how is it possible to compare values in these methods i.e.

if(node.o < o) {...}

I tried to use compareTo i.e.

if(node.o.compareTo(o) > 0) {...}

but I think i have misunderstood something. Someone suggessted using Comparable interface but I do not know where to start.

[470 byte] By [katerinea] at [2007-10-1 6:05:48]
# 1

Two standard ways to do this are to pass in a Comparator object into the constructor of the Tree, or to have every object inserted into the tree implement the Comparable interface.

So, in your example you would do something like:

insert(Object o) {

if (comparator != null) {

insertByComparator(o);

return;

}

if (o instanceof Comparable) {

Comparable c = (Comparable) o;

// ....

}

else

throw new IllegalArgumentException("inserted object must implement java.util.Comparable")

}

rkippena at 2007-7-9 14:23:02 > top of Java-index,Other Topics,Algorithms...