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.
- Ternary Search Tree
- Longest word in ternary search tree
- AVL Tree | Set 2 (Deletion)
- Convert Ternary Expression to a Binary Tree
- Deletion in a Binary Tree
- Create a Doubly Linked List from a Ternary Tree
- Convert ternary expression to Binary Tree using Stack
- Van Emde Boas Tree | Set 4 | Deletion
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Minimum swap required to convert binary tree to binary search tree
- Splay Tree | Set 1 (Search)
- Search a node in Binary Tree
- Iterative Search for a key 'x' in Binary Tree
- K Dimensional Tree | Set 1 (Search and Insert)
- Sum of all the levels in a Binary Search Tree