Skip to content
Related Articles

Related Articles

Trie | (Display Content)

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 25 May, 2022

Trie is an efficient information retrieval data structure. In our previous post on trie we have discussed about basics of trie and how to insert and search a key in trie. In this post we will discuss about displaying all of the content of a trie. That is, to display all of the keys present in the Trie.

Input: If Trie is      root
                    /   \    \
                    t   a     b
                    |   |     |
                    h   n     y
                    |   |  \  |
                    e   s  y  e
                 /  |   |
                 i  r   w
                 |  |   |
                 r  e   e
Output: Contents of Trie:


The idea to do this is to start traversing from the root node of trie, whenever we find a NON-NULL child node, we add parent key of child node in the “string str” at the current index(level) and then recursively call the same process for the child node and same goes on till we find the node which is a leafnode, which actually marks the end of the string. 
Below is the C++ implementation of above idea: 


// CPP program to display content of Trie
#include <iostream>
#include <string.h>
#define alpha_size 26
#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])
using namespace std;
// Trie node
struct TrieNode 
    struct TrieNode* children[alpha_size];
    bool isLeaf;
// Returns new trie node (initialized to NULLs)
struct TrieNode* createNode()
    struct TrieNode* pNode = new TrieNode;
    for (int i = 0; i < alpha_size; i++)
        pNode->children[i] = NULL;
    pNode->isLeaf = false;
    return pNode;
// function to insert a node in Trie
void insert_node(struct TrieNode* root, char* key)
    int level;
    int length = strlen(key);
    struct TrieNode* pCrawl = root;
    for (level = 0; level < length; level++) 
        int index = key[level] - 'a';
        if (pCrawl->children[index] == NULL)
            pCrawl->children[index] = createNode();
        pCrawl = pCrawl->children[index];
    pCrawl->isLeaf = true;
// function to check if current node is leaf node or not
bool isLeafNode(struct TrieNode* root)
    return root->isLeaf != false;
// function to display the content of Trie
void display(struct TrieNode* root, char str[], int level)
    // If node is leaf node, it indicates end
    // of string, so a null character is added
    // and string is displayed
    if (isLeafNode(root)) 
        str[level] = '\0';
        cout << str << endl;
    int i;
    for (i = 0; i < alpha_size; i++) 
        // if NON NULL child is found
        // add parent key to str and
        // call the display function recursively
        // for child node
        if (root->children[i]) 
            str[level] = i + 'a';
            display(root->children[i], str, level + 1);
// Driver program to test above functions
int main()
    // Keys to be inserted in Trie
    char keys[][8] = { "the", "a", "there", "answer",
                       "any", "by", "bye", "their" };
    struct TrieNode* root = createNode();
    // Inserting keys in Trie
    for (int j = 0; j < ARRAY_SIZE(keys); j++)
        insert_node(root, keys[j]);
    int level = 0;
    char str[20];
    // Displaying content of Trie
    cout << "Content of Trie: " << endl;
    display(root, str, level);


##Display words in a trie (recursive approach)
class TrieNode:
    def __init__(self):
class Trie:
    def __init__(self):
    def getNode(self):
        return TrieNode()
    def _charToIndex(self,ch):
        return ord(ch)-ord('a')
    def search(self,key):
        for level in range(length):
            if not pCrawl.children[index]:
                return False
        return pCrawl.isEndOfWord
    def insert(self,key):
        for level in range(length):
            if not pCrawl.children[index]:
    def delete(self,key):
        for level in range(length):
            if not pCrawl.children[index]:
            if pCrawl.isEndOfWord:
        if pCrawl.isEndOfWord == False:
        ##If is a prefix of another tree, just change leaf
        for i in range(26):
            if pCrawl.children[index]:
        if flag:
        ##If not a prefix but a tree longer than others, delete until isEndOfWord == True again/reach root(a unique trie)
        if len(queue)==0:
    def haschild(self,node):
        for i in range(26):
            if node.children[i]:
                return True
        return False
    def displayUtil(self,visited,node,str):
        while index<26:
            if node.children[index]:
                if node.children[index].isEndOfWord == False:
                    str=str[0 : (len(str)-1)]
                    if str not in visited:
                    if self.haschild(node.children[index]):
                        str=str[0 : (len(str)-1)]
    def display(self):
        print("Content of Trie:")
        for i in range(len(visited)):
keys = ["the","a","there","bye","any",
output = ["Not present in trie","Present in trie"]
for key in keys:
#This code is contributed by Zhaoxin Ban


Content of Trie:

NOTE: The above algorithm displays the content of Trie in Lexicographically Sorted order.
Some useful applications of Trie are: 

This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!