R@M3\$H.NBlog

# TST (Ternary Search Tree)

### 20 January, 2014 - 16 min read

A ternary search tree is a special trie data structure where the child nodes of a standard trie are ordered as a binary search tree.

Representation of ternary search trees:
Unlike trie(standard) data structure where each node contains 26 pointers for its children, each node in a ternary search tree contains only 3 pointers:

1. The left pointer points to the node whose value is less than the value in the current node.
2. The equal pointer points to the node whose value is equal to the value in the current node.
3. The right pointer points to the node whose value is greater than the value in the current node.

Apart from above three pointers, each node has a field to indicate data(character in case of dictionary) and another field to mark end of a string.
So, more or less it is similar to BST which stores data based on some order. However, data in a ternary search tree is distributed over the nodes. e.g. It needs 4 nodes to store the word “Geek”.
Below figure shows how exactly the words in a ternary search tree are stored?

One of the advantage of using ternary search trees over tries is that ternary search trees are a more space efficient (involve only three pointers per node as compared to 26 in standard tries). Further, ternary search trees can be used any time a hashtable would be used to store strings.

Tries are suitable when there is a proper distribution of words over the alphabets so that spaces are utilized most efficiently. Otherwise ternary search trees are better. Ternary search trees are efficient to use(in terms of space) when the strings to be stored share a common prefix.

Applications of ternary search trees:
__1. __Ternary search trees are efficient for queries like “Given a word, find the next word in dictionary(near-neighbor lookups)” or “Find all telephone numbers starting with 9342 or “typing few starting characters in a web browser displays all website names with this prefix”(Auto complete feature)”.

__2. __Used in spell checks: Ternary search trees can be used as a dictionary to store all the words. Once the word is typed in an editor, the word can be parallely searched in the ternary search tree to check for correct spelling.

Implementation:
Following is C implementation of ternary search tree. The operations implemented are, search, insert and traversal.

`   1: // C program to demonstrate Ternary Search Tree (TST) insert, travese `

`   2:`

`   3: // and search operations`

`   4:`

`   5: #include <stdio.h>`

`   6:`

`   7: #include <stdlib.h>`

`   8:`

`   9: #define MAX 50`

`  10:`

`  11: // A node of ternary search tree`

`  12:`

`  13: struct Node`

`  14:`

`  15: {`

`  16:`

`  17: char data;`

`  18:`

`  19: // True if this character is last character of one of the words`

`  20:`

`  21: unsigned isEndOfString: 1;`

`  22:`

`  23: struct Node *left, *eq, *right;`

`  24:`

`  25: };`

`  26:`

`  27: // A utility function to create a new ternary search tree node`

`  28:`

`  29: struct Node* newNode(char data)`

`  30:`

`  31: {`

`  32:`

`  33: struct Node* temp = (struct Node*) malloc(sizeof( struct Node ));`

`  34:`

`  35: temp->data = data;`

`  36:`

`  37: temp->isEndOfString = 0;`

`  38:`

`  39: temp->left = temp->eq = temp->right = NULL;`

`  40:`

`  41: return temp;`

`  42:`

`  43: }`

`  44:`

`  45: // Function to insert a new word in a Ternary Search Tree`

`  46:`

`  47: void insert(struct Node** root, char *word)`

`  48:`

`  49: {`

`  50:`

`  51: // Base Case: Tree is empty`

`  52:`

`  53: if (!(*root))`

`  54:`

`  55: *root = newNode(*word);`

`  56:`

`  57: // If current character of word is smaller than root's character,`

`  58:`

`  59: // then insert this word in left subtree of root`

`  60:`

`  61: if ((*word) < (*root)->data)`

`  62:`

`  63: insert(&( (*root)->left ), word);`

`  64:`

`  65: // If current character of word is greate than root's character,`

`  66:`

`  67: // then insert this word in right subtree of root`

`  68:`

`  69: else if ((*word) > (*root)->data)`

`  70:`

`  71: insert(&( (*root)->right ), word);`

`  72:`

`  73: // If current character of word is same as root's character,`

`  74:`

`  75: else`

`  76:`

`  77: {`

`  78:`

`  79: if (*(word+1))`

`  80:`

`  81: insert(&( (*root)->eq ), word+1);`

`  82:`

`  83: // the last character of the word`

`  84:`

`  85: else`

`  86:`

`  87: (*root)->isEndOfString = 1;`

`  88:`

`  89: }`

`  90:`

`  91: }`

`  92:`

`  93: // A recursive function to traverse Ternary Search Tree`

`  94:`

`  95: void traverseTSTUtil(struct Node* root, char* buffer, int depth)`

`  96:`

`  97: {`

`  98:`

`  99: if (root)`

` 100:`

` 101: {`

` 102:`

` 103: // First traverse the left subtree`

` 104:`

` 105: traverseTSTUtil(root->left, buffer, depth);`

` 106:`

` 107: // Store the character of this node`

` 108:`

` 109: buffer[depth] = root->data;`

` 110:`

` 111: if (root->isEndOfString)`

` 112:`

` 113: {`

` 114:`

` 115: buffer[depth+1] = '';`

` 116:`

` 117: printf( "%s\n", buffer);`

` 118:`

` 119: }`

` 120:`

` 121: // Traverse the subtree using equal pointer (middle subtree)`

` 122:`

` 123: traverseTSTUtil(root->eq, buffer, depth + 1);`

` 124:`

` 125: // Finally Traverse the right subtree`

` 126:`

` 127: traverseTSTUtil(root->right, buffer, depth);`

` 128:`

` 129: }`

` 130:`

` 131: }`

` 132:`

` 133: // The main function to traverse a Ternary Search Tree.`

` 134:`

` 135: // It mainly uses traverseTSTUtil()`

` 136:`

` 137: void traverseTST(struct Node* root)`

` 138:`

` 139: {`

` 140:`

` 141: char buffer[MAX];`

` 142:`

` 143: traverseTSTUtil(root, buffer, 0);`

` 144:`

` 145: }`

` 146:`

` 147: // Function to search a given word in TST`

` 148:`

` 149: int searchTST(struct Node *root, char *word)`

` 150:`

` 151: {`

` 152:`

` 153: if (!root)`

` 154:`

` 155: return 0;`

` 156:`

` 157: if (*word < (root)->data)`

` 158:`

` 159: return searchTST(root->left, word);`

` 160:`

` 161: else if (*word > (root)->data)`

` 162:`

` 163: return searchTST(root->right, word);`

` 164:`

` 165: else`

` 166:`

` 167: {`

` 168:`

` 169: if (*(word+1) == '')`

` 170:`

` 171: return root->isEndOfString;`

` 172:`

` 173: return searchTST(root->eq, word+1);`

` 174:`

` 175: }`

` 176:`

` 177: }`

` 178:`

` 179: // Driver program to test above functions`

` 180:`

` 181: int main()`

` 182:`

` 183: {`

` 184:`

` 185: struct Node *root = NULL;`

` 186:`

` 187: insert(&root, "cat");`

` 188:`

` 189: insert(&root, "cats");`

` 190:`

` 191: insert(&root, "up");`

` 192:`

` 193: insert(&root, "bug");`

` 194:`

` 195: printf("Following is traversal of ternary search tree\n");`

` 196:`

` 197: traverseTST(root);`

` 198:`

` 199: printf("\nFollowing are search results for cats, bu and cat respectively\n");`

` 200:`

` 201: searchTST(root, "cats")? printf("Found\n"): printf("Not Found\n");`

` 202:`

` 203: searchTST(root, "bu")?   printf("Found\n"): printf("Not Found\n");`

` 204:`

` 205: searchTST(root, "cat")?  printf("Found\n"): printf("Not Found\n");`

` 206:`

` 207: return 0;`

` 208:`

` 209: }`

` 210:`

` 211: Output:`

` 212:`

` 213: Following is traversal of ternary search tree`

` 214: bug`

` 215: cat`

` 216: cats`

` 217: up`

` 218:`

` 219: Following are search results for cats, bu and cat respectively`

` 220: Found`

` 221: Not Found`

` 222: Found`

Time Complexity: The time complexity of the ternary search tree operations is similar to that of binary search tree. i.e. the insertion, deletion and search operations take time proportional to the height of the ternary search tree. The space is proportional to the length of the string to be stored.