The Wayback Machine - https://web.archive.org/web/20240723151234/https://www.geeksforgeeks.org/trie-data-structure-using-smart-pointer-and-oop-in-c/
Open In App

Trie Data Structure using smart pointer and OOP in C++

Last Updated : 08 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursion
In our implementation node of a trie look like : 

CPP




class TrieNode{
 
    public:
    // Use of shared_ptr for storing Children
    // Pointers of TrieNode
 
    shared_ptr children[ALPHABET_SIZE];
 
    // Tracks whether If this Node is the end of
    // any word stored in Trie
 
    bool isWord;
 
    // Constructor for TrieNode
    TrieNode()
    {
        for(int i=0; i<ALPHABET_SIZE; i++)
        {
            children[i] = shared_ptr();
        }
        isWord = false;
    }
};


The interface is the class showing the functionalities of our object class which has only pure virtual functions. Here, the concept interface discussed in more detail.
 

CPP




// Interface representing functionalities
// of Trie Data Structure
class interface {
public:
    interface() {}
    virtual ~interface() {}
    // Pure virtual functions showing all
    // the functions of my Trie class
  
    // To convert character to integer like hashing
    virtual int i2c(char) = 0;
  
    // Inserts word to Trie
    virtual void insertWord(string&) = 0;
  
    // Deletes word if present
    virtual bool deleteWord(string&) = 0;
  
    // To search a word in Trie
    virtual bool searchWord(string&) = 0;
  
    // Checks whether there is any children present
    // for any node
    virtual bool isEmptyNode(shared_ptr<TrieNode>)
                                          const = 0;
};


nullptrs stores NULL which suggests that there is no path for any other string from that position
Below image shows the insertion of “geeks” into an empty trie. 
 

Below image shows the insertion of “geeksfor” into the trie. geeks p is already exiting in the trie. so, it overlaps.
 

Below image shows the insertion of “trie” into the trie
 

Why shared_ptr instead of all other smart pointers (auto_ptr, unique_ptr, weak_ptr)?
We are using shared_ptr due to the fact that while constructing the Trie we may encounter a situation where we may have to share the resource of a particular pointer to the other temporary shared_ptr to traverse Trie. In that shared_ptr is better than any other above mentioned pointers.
Below is the implementation of the above approach :
 

CPP




#include <iostream>
 
// For shared_ptr class
#include <memory>
 
using namespace std;
#define ALPHABET_SIZE 26
 
// Trie Node class
class TrieNode {
 
public:
    // Use of shared_ptr for storing Children
    // Pointers of TrieNode
 
    shared_ptr<TrieNode> children[ALPHABET_SIZE];
 
    // Tracks whether If this Node is the end of
    // any word stored in Trie
 
    bool isWord;
 
    // Constructor for TrieNode
    TrieNode()
    {
        for (int i = 0; i < ALPHABET_SIZE; i++) {
            children[i] = shared_ptr<TrieNode>();
        }
        isWord = false;
    }
};
 
// Interface representing functionalities
// of Trie Data Structure
class interface {
public:
    interface() {}
    virtual ~interface() {}
    // Pure virtual functions showing all
    // the functions of my Trie class
 
    // To convert character to integer like hashing
    virtual int i2c(char) = 0;
 
    // Inserts word to Trie
    virtual void insertWord(string&) = 0;
 
    // Deletes word if present
    virtual bool deleteWord(string&) = 0;
 
    // To search a word in Trie
    virtual bool searchWord(string&) = 0;
 
    // Checks whether there is any children present
    // for any node
    virtual bool isEmptyNode(shared_ptr<TrieNode>)
                                          const = 0;
};
 
class Trie : public interface {
     
    // Storing root of the Trie
    shared_ptr<TrieNode> root;
    int Total_words;
 
public:
    Trie()
    {
        root = shared_ptr<TrieNode>
                              (new TrieNode());
        Total_words = 0;
    }
 
    ~Trie()
    {
        // Need not delete anything
                // as shared_ptr deallocates
                // all memory automatically
    }
 
    // To convert characters of string into
    // integer like hashing of character
    int i2c(char c)
    {
        return static_cast<int>(c - 'a');
    }
 
    // Insert word function
    void insertWord(string& trieString)
    {
        shared_ptr<TrieNode> current = root;
        for (int i = 0; i < trieString.size(); i++)
                {
             
            // If word after some prefix is not
                        // present then creates new node
            if (current->children[i2c(trieString[i])] ==
                          shared_ptr<TrieNode>(nullptr))
            {
                current->children[i2c(trieString[i])] =
                     shared_ptr<TrieNode>(new TrieNode());
            }
            current = (current->children[i2c(trieString[i])]);
        }
 
        // Now word is added in Trie so at leaf node
        // for that word isWord=true
        current->isWord = true;
    }
 
    // Searching for word whether it is
    // present in Trie
    bool searchWord(string& trieString)
    {
        shared_ptr<TrieNode> current = root;
 
        for (int i = 0; i < trieString.size(); i++)
        {
            // If at any point in Trie Node for particular
            // character is not present means nullptr then
            // return false
            if (current->children[i2c(trieString[i])] ==
                            shared_ptr<TrieNode>(nullptr))
                return false;
            current = current->children[i2c(trieString[i])];
        }
 
        // At the end of the word checking whether this
        // word is really present or not
        if (current->isWord == true)
            return true;
 
        return false;
    }
 
    bool Partdelete(string& trieString, shared_ptr<TrieNode>&     
                                                     checkout)
    {
        // Word is not present in the Trie then returns
        // false and stops further recursion
        if (checkout == nullptr)
            return false;
 
        // At the end of the word if the word is
        // present in trie then setting isWord to
        // false either returning false
        if (trieString.size() == 0) {
            if (checkout->isWord == true) {
                checkout->isWord = false;
                return true;
            }
            return false;
        }
 
        // String excluding first character
        string part = trieString.substr(1);
 
        // Recursive call to Partdelete for
        // rest of the string(part)
        if (Partdelete(part, checkout->
                      children[i2c(trieString[0])])) {
                           
            // Checks whether it is empty node
            // then delete this node
            if (isEmptyNode(checkout->
                      children[i2c(trieString[0])])) {
                           
                // Resetting memory and making it nullptr
                checkout->children[i2c(trieString[0])].
                                                 reset();
                                                  
                checkout->children[i2c(trieString[0])] =
                                                  nullptr;
                 
                return true;
            }
            else
                return true;
        }
        else
            return false;
 
        return false;
    }
 
    // For ease of recursion; passing
    // root to Partdelete
    bool deleteWord(string& trieString)
    {
        if (Partdelete(trieString, root))
            return true;
        return false;
    }
 
    // Checks whether there is no children present
    bool isEmptyNode(shared_ptr<TrieNode> check) const
    {
        for (int i = 0; i < ALPHABET_SIZE; i++) {
            if (check->children[i] != nullptr ||
                              check->isWord == true)
                return false;
        }
        return true;
    }
};
 
// Driver code
int main()
{
    // Again using shared_ptr to store Trie
    // you can use auto_ptr here
    shared_ptr<Trie> myTrie(new Trie());
 
    string word1 = "geeksfor";
    string word2 = "geeksforgeeks";
    string word3 = "nothing";
 
    myTrie->insertWord(word1);
 
    if (myTrie->searchWord(word1))
        cout << word1 << ": Is Present" << endl;
    else
        cout << word1 << ": Not Present" << endl;
 
    if (myTrie->searchWord(word3))
        cout << word3 << ": Is Present" << endl;
    else
        cout << word3 << ": Not Present" << endl;
 
    myTrie->insertWord(word2);
 
    if (myTrie->deleteWord(word2))
        cout << word2 << ": Successfully deleted" << endl;
    else
        cout << word2 << ": Not Present" << endl;
 
    if (myTrie->searchWord(word2))
        cout << word2 << ": Is Present" << endl;
    else
        cout << word2 << ": Not Present" << endl;
 
}


Output: 

geeksfor: Is Present
nothing: Not Present
geeksforgeeks: Successfully deleted
geeksforgeeks: Not Present

 

Time Complexity:  O(n*s) where n is the number of words and s is the maximum length of the word in the list of words.
Auxiliary Space:  O(n*ALPHABET_SIZE)



Similar Reads

C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator. Syntax of a Pointer in C++: data_type_of_pointer *name_of_variable = &amp; normal_variable; What is a Pointer to a Pointer or Double Pointer
4 min read
Trie Data Structure | Insert and Search
The Trie data structure is a tree-like data structure used for storing a dynamic set of strings. It is commonly used for efficient retrieval and storage of keys in a large dataset. The structure supports operations such as insertion, search, and deletion of keys, making it a valuable tool in fields like computer science and information retrieval. I
14 min read
Advantages of Trie Data Structure
Introduction: Trie (also known as prefix tree) is a tree-based data structure that is used to store an associative array where the keys are sequences (usually strings). Some advantages of using a trie data structure include:Fast search: Tries support fast search operations, as we can search for a key by traversing down the tree from the root, and t
8 min read
Trie Data Structure in C++
A Trie, also known as a prefix tree, is a tree-like data structure used to store a dynamic set of strings. It is particularly useful for efficient retrieval of keys in a large dataset of strings. In this article, we will explore the Trie data structure, its operations, implementation in C++, and its advantages, disadvantages, and applications. What
8 min read
Advantages and Disadvantages of OOP
OOP stands for Object-Oriented Programming. As you can guess from it's name it breaks the program on the basis of the objects in it. It mainly works on Class, Object, Polymorphism, Abstraction, Encapsulation and Inheritance. Its aim is to bind together the data and functions to operate on them. Some of the well-known object-oriented languages are O
3 min read
How to create a pointer to another pointer in a linked list?
In this article we cover how to create a pointer to another pointer in a linked list, it can be singly, doubly, or circularly. What is Linked List: A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Singly
7 min read
Overview of Graph, Trie, Segment Tree and Suffix Tree Data Structures
Introduction:Graph: A graph is a collection of vertices (nodes) and edges that represent relationships between the vertices. Graphs are used to model and analyze networks, such as social networks or transportation networks.Trie: A trie, also known as a prefix tree, is a tree-like data structure that stores a collection of strings. It is used for ef
10 min read
Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
C++ - Pointer to Structure
Pointer to structure in C++ can also be referred to as Structure Pointer. A structure Pointer in C++ is defined as the pointer which points to the address of the memory block that stores a structure. Below is an example of the same: Syntax: struct name_of_structure *ptr; // Initialization of structure is done as shown below ptr = &amp;structure_var
2 min read
Sorting array of strings (or words) using Trie | Set-2 (Handling Duplicates)
Given an array of strings, print them in alphabetical (dictionary) order. If there are duplicates in input array, we need to print all the occurrences.Examples: Input : arr[] = { "abc", "xyz", "abcd", "bcd", "abc" } Output : abc abc abcd bcd xyz Input : arr[] = { "geeks", "for", "geeks", "a", "portal", "to", "learn" } Output : a for geeks geeks lea
9 min read
three90RightbarBannerImg