lollercopter
lollercopter

Reputation: 111

Arranging strings alphabetically in binary tree

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

Upvotes: 0

Views: 5636

Answers (2)

Aidanc
Aidanc

Reputation: 7011

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.

Upvotes: 2

Hot Licks
Hot Licks

Reputation: 47729

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

Upvotes: 0

Related Questions