Ternary Search Trees are specialized structures used to store strings so they are easily searchable.
- The traversal of the tree proceeds character by character
- Each node can have up to three children ( as opposed to two in binary trees)
- Middle node connection is dotted.
- Nodes that form the end of a word are colored.
An insert compares the current character in the string to be inserted (insert character) with the current character at the node (node character):
- If the insert character is less than the node’s character then the insertion is made to the left (the line between nodes is solid)
- If the insert character is greater than the node’s character then the insertion is made to the right(the line between nodes is solid)
- If the insert character is equal to the node’s character then the insertion is made to the middle child and proceeds to the next character in the string to be inserted (or the next insert character).(the line between nodes is dotted)
We begin with AB. We insert A and then B is a child so a dotted line is drawn between the two :
Now we wish to store string ABBA. We try to insert A. We find it is already there so we move to B in and notice that B is also already in the tree. Then we insert the rest of the string "ABBA" which is B and A :
Then we insert the next string: ABCD. We try to insert A and we find A. So we move to the next node in the tree B. Then we try to insert B and we find B in the tree so we move to the next node in the tree, again a B. Then we try to insert C and we find that we are on the second B or the third node. So to insert C we take a right branch and insert C and then insert D.
Now we try to insert BCD and as we enter the tree we encounter the first node character A which is not the same as the first character of the string BCD which is B. We insert B to the right branch of A so:
- If the search character is less than the node’s character then the search goes to the left
- If the search character is greater than the node’s character then the search goes to the right
- If the search character is equal to the node’s character then the search goes down to the middle child and proceeds to the next character in the search string (or the next search character).
If we searched for ABD we would be unable to find it:
Another example of a ternary search tree is the following:
In the above don’t be surprised by the far left location of the first word “as” it is merely shifted left.
No comments:
Post a Comment