Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes searching method for  a Binary Search Tree Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "searching method for  a Binary Search Tree" Watch "searching method for  a Binary Search Tree" New topic
Author

searching method for a Binary Search Tree

anmadi house
Greenhorn

Joined: Dec 09, 2009
Posts: 2
I have created a tree ( contains name and age)

now i have to create a method that takes the name as an input searches the tree and returns name and age.

i am not sure how to start this task.

Thank you for time and ideas.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11229
    
  16

is your tree sorted in any way? if not, you'll have to traverse every node looking for the one you want.

if it is, you can start at the root, and move to whichever child would be correct based on your comparison.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
anmadi house
Greenhorn

Joined: Dec 09, 2009
Posts: 2
i used inorderTraversal to print the names and ages alphabetical order.



Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
The generic search algorithm for a BST is something like this:



You can use String.compareTo() for the conditionals.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: searching method for a Binary Search Tree