• Post Reply Bookmark Topic Watch Topic
  • New Topic

Binary Search Tree Lookup Method  RSS feed

 
Stephane Bonett
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, I'm having a bit of trouble creating the search method for the BST. I've come up with the following:



BNode


I need to create a getKey method to BNode so that I can get the key of the currentNode so than I can compare string against string. How do I go about doing this?

Thanks
 
Martin Vajsar
Sheriff
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A better way would be to require the key to implement the Comparable interface. Conversion to String to do the comparison is fraught with errors (numbers won't compare in the correct order, and worse, the same number can have different String representations). You would then call compareTo directly on the key.

Another possibility would be to allow the user to provide a Comparator to actually compare the keys. Both approaches can be easily combined. You might want to have a look at JDK source of TreeSet/TreeMap to see how that can be done.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!