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?)

- 8,084
- 8
- 48
- 62

- 111
- 3
- 12
-
3"Any assistance is appreciated!" - assistance with what? I don't see any code... – Mitch Wheat Apr 09 '12 at 01: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 Apr 09 '12 at 01:57
-
1@lollercopter You say you've done this with numbers.. nothing changes with Strings. Your comparison is now alphabetical is all.. check http://stackoverflow.com/questions/6203411/comparing-strings-by-their-alphabetical-order for coming up with a comparison function. – Aidanc Apr 09 '12 at 02: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.
You don't enter stuff into a binary tree "alphabetically", you simply enter stuff into the tree. The tree does the sorting. (Keep in mind that a character string is just a sequence of numbers.)

- 47,103
- 17
- 93
- 151