Ternary Search Tree (Deletion)
In the SET 1 post on TST we have described how to insert and search a node in TST. In this article we will discuss algorithm on how to delete a node from TST.
During delete operation we delete the key in bottom up manner using recursion. The following are possible cases when deleting a key from trie.
- Key may not be there in TST.
Solution : Delete operation should not modify TST.
- Key present as unique key (no part of key contains another key (prefix), nor the key itself is prefix of another key in TST).
Solution : Delete all the nodes.
- Key is prefix key of another long key in TST.
Solution : Unmark the leaf node.
- Key present in TST, having atleast one other key as prefix key.
Solution : Delete nodes from end of key until first leaf node of longest prefix key.
Explanation for delete_node function
- Let suppose we want to delete string “BIG”,since it is not present in TST so after matching with first character ‘B’, delete_node function will return zero. Hence nothing is deleted.
- Now we want to delete string “BUG”, it is Uniquely present in TST i.e neither it has part which is the prefix of other string nor it is prefix to any other string, so it will be deleted completely.
- Now we want to delete string “CAT”, since it is prefix of string “CATS”, we cannot delete anthing from the string “CAT” and we can only unmark the leaf node which will ensure that “CAT” is no longer a member string of TST.
- Now we want to delete string “CATS”, since it has a prefix string “CAT” which also is a member string of TST so we can only delete last character of string “CATS” which will ensure that string “CAT” still remains the part of TST.
1.Content of the TST before deletion: BUGS CAT CATS UP 2.Content of the TST after deletion: BUGS CATS UP
This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.