I am constructing a binary tree consisting of words from a sample paragraph, sorted alphabetically. So far, I have implemented all of the basic "behind the scenes" work to define the binary tree (constructors, methods), and I am now working on adding elements (words) to the tree.
Every word has had its non-alphanumeric characters removed and every letter in the word is converted to lowercase. I am wondering how I could enter words into the tree alphabetically? All I have done with binary trees have to do with numbers, so I am not sure what to do in this case. (I was thinking of something to do with ASCII values?)
-
3"Any assistance is appreciated!" - assistance with what? I don't see any code...Mitch Wheat– Mitch Wheat2012-04-09 01:53:19 +00:00Commented Apr 9, 2012 at 1:53
-
I'm asking about a general algorithm on how to do this. I haven't coded anything yet, I'm still in the problem solving stages.lollercopter– lollercopter2012-04-09 01:57:27 +00:00Commented Apr 9, 2012 at 1:57
-
1@lollercopter You say you've done this with numbers.. nothing changes with Strings. Your comparison is now alphabetical is all.. check stackoverflow.com/questions/6203411/… for coming up with a comparison function.Aidanc– Aidanc2012-04-09 02:00:32 +00:00Commented Apr 9, 2012 at 2:00
2 Answers
You say you've done this with numbers before.
Nothing has really changed with your new tree.
You can think of an alphabetical comparison as just a way of giving something a precedence ranking over something else.
So, think of these strings as being a number, the smaller the number, the lower level in the tree the string will occupy. You're simply making your tree sort by smallest numbers first. A is smaller than B, B is smaller than C and so on.
Check out this related question for coming up with a comparison function to give you the "numbers" you're looking for.