Monday 13 April 2015

Trie Insert and Search

#include<iostream>
#include<string.h>

#define CHAR_TO_INDEX(c) int(c)-int('a')


using namespace std;

struct trie_node
{
    int value;
    trie_node* children[26];
};


class trie
{
    public:
        trie_node * root;
        int count;
        trie()
        {
            root = new trie_node();
            root->value = 0;

            for(int i=0; i < 26; i++)
                root->children[i] = NULL;
        }

        void insert_node(char key[]);
        trie_node* getNode();
        bool search(char key[]);

};

trie_node* trie::getNode()
{
    trie_node * root;
    root = new trie_node();
    root->value = 0;
    for(int i=0; i < 26; i++)
        root->children[i] = NULL;

    return root;

}

void trie::insert_node(char key[])
{
    int len = strlen(key);
    trie_node* pcrawl;
    count++;
    pcrawl = root;
    int index;
    for(int i = 0; i < len; i++)
    {
        index = CHAR_TO_INDEX(key[i]);

        if(pcrawl->children[index] == NULL)
        {
            pcrawl->children[index] = getNode();

        }
        pcrawl = pcrawl->children[index];

    }
    pcrawl->value = count;


}

bool trie::search(char key[])
{
    trie_node *pcrwal = root;
    int len = strlen(key);
    int index;
    int i;

    for(i = 0; i<len; i++)
    {
        index = CHAR_TO_INDEX(key[i]);
        if(pcrwal->children[index] != NULL)
        {
            pcrwal = pcrwal->children[index];
        }
        else
        {
            break;
        }

    }

    // just check wheather we have find the pattern in trie

    if (i<len)
        return false;
    else
        if(pcrwal->value > 0)
            return true;
        else
            return false;

}



int main()
{
    // Input keys (use only 'a' through 'z' and lower case)
    char keys[][8] = {"the", "a", "there", "answer", "any", "by", "bye", "their"};
    char output[][32] = {"Not present in trie", "Present in trie"};

    trie* mytrie = new trie();
    mytrie ->insert_node("wasim");
    mytrie ->insert_node("warish");
    mytrie ->insert_node("koser");

    if(mytrie->search("wasim"))
        cout<<"Found";
    else
        cout<<"Not Found";


    return 0;
}