All about Trie Data Structure

// trei is a data structure which has an array and a leaf 
// array points to the next tries and leaf 
// tells whether this word ends or not.

#include <bits/stdc++.h>
using namespace std;
 


class Node{
    public:
    Node* arr[26];
    bool leaf;

    Node(){
        for(int i=0;i<26;i++) arr[i] = NULL;
        leaf = false;
    }

};


//recursive functions:
void addHelper(Node* rootstring &wordint idx){
    //base case:
    if(idx == word.size()){
        root->leaf = true;
        return;
    }

    // check if word[idx] exists:
    if(root->arr[word[idx] - 'a'== NULL){
        root->arr[word[idx] - 'a'= new Node();   //make new
        // cout << word[idx] << " ";
    }

    //and call for next idx:
    addHelper(root->arr[word[idx] - 'a'], wordidx+1);
    return;
}

void add(Node* rootstring &word){
    addHelper(rootword0);
}




//find function:
bool findHelper(Node* rootstring &wordint idx){
    if(idx >= word.size()) return root->leaf;

    // check if exists -> not -> false:
    if(root->arr[word[idx] - 'a'== NULLreturn false;
    
    //call for next idx:
    return findHelper(root->arr[word[idx] - 'a'], wordidx+1);
}

bool find(Node* rootstring &word){
    return findHelper(rootword0);
}


// print a Trie:
void displayHelper(Node* rootstring str){
    if(root->leaf){
        // end:-> add end char and take the string:
        // str += '\0';
        cout << str << endl;
        return;
    }

    // run a loop for all possible children:
    for(int i=0;i<26;i++){
        if(root->arr[i]){
            // str += i + 'a';
            string n = str;
            n += (i + 'a');
            displayHelper(root->arr[i], n); //call for next:
        }
    }

    return;
}

void display(Node* root){
    string str = "";
    displayHelper(root, str);    
}



int main(){
    cout << "Code is running" << endl;
    Node* root = new Node();
    vector<string> v = {"tejas""suraj""tushar""shrey""yash"};

    for(auto word: v) add(root, word);
    // add(root, v[0]);
    // for(auto w: v){
    //     find(root, w) ? cout << "Yes" << endl : cout << "No" << endl; 
    // }
    // string s = "texas";
    // cout << find(root, s);

    display(root);

    return 0;
}

Comments

Popular Posts