Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length).
Given a trie. The task is to print the characters in a bottom-up manner
First print string of left most subtree(from bottom to top) then print string of second left subtree(from bottom to top) then print for third left subtree and so on.
It is similar to post-order traversal of a tree
Input : root / \ a t | | n h | \ | s y e | | \ w i r | | | e r e | r Output : r, e, w, s, y, n, a, r, i, e, r, e, h, t Input : root / \ c t | | a h | \ | l t e | | \ l i r | \ | | e i r e | | r n | g Output : r, e, g, n, i, l, l, t, a, c, r, i, e, r, e, h, t
In the first example, the root has two parts. First part contains strings: “answer” and “any”.
the second part with strings “their” and “there”.
- Now first we got to left subtree containing strings “answer” and “any” which separates by character ‘n’. Now ‘n’ separates two-part of characters ‘s’, ‘w’, ‘e’, ‘r’ and ‘y’. so print ‘s’, ‘w’, ‘e’, ‘r’ in reverse order then print ‘y’ and go up and print ‘n'(which separates string) then go up and print ‘a’. Now first left subtree has printed in bottom up manner ‘r’, ‘e’, ‘w’, ‘s’, ‘y’, ‘n’, ‘a’.
- Do the same thing for another subtree of the root which contains strings “their” and “there” which is separated by character ‘e’.
The idea to do this is to start traversing from the root node of the trie, whenever we find a NON-NULL child node, we recursively move ahead when we get “NULL” we return simply and print the value of current node and same goes un till we find the node which is a leaf node, which actually marks the end of the string.
Below is the implementation of the above approach :
r, e, w, s, y, n, a, e, r, e, r, e, i, h, t,
- Boggle | Set 2 (Using Trie)
- Trie | (Delete)
- Search in a trie Recursively
- Persistent Trie | Set 1 (Introduction)
- Trie | (Display Content)
- Implement a Dictionary using Trie
- Insertion in a Trie recursively
- Trie | (Insert and Search)
- Pattern Searching using a Trie of all Suffixes
- Counting the number of words in a Trie
- Longest Common Prefix using Trie
- Advantages of Trie Data Structure
- Trie memory optimization using hash map
- Program for assigning usernames using Trie
- Count inversions in an array | Set 4 ( Using Trie )
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.