Skip to content

Instantly share code, notes, and snippets.

@hrsvrdhn
Created August 8, 2017 07:12
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrsvrdhn/1ae71c25ef1c620c022a544d52df8928 to your computer and use it in GitHub Desktop.
Save hrsvrdhn/1ae71c25ef1c620c022a544d52df8928 to your computer and use it in GitHub Desktop.
Trie implementation in C++
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
#include<map>
using namespace std;
struct TrieNode
{
map<char,TrieNode*> children;
int prefixes;
bool endofword;
TrieNode()
{
prefixes=0;
endofword=false;
}
};
void insert(TrieNode *root,string word)
{
TrieNode *current=root;
for(int i=0;i<word.size();i++)
{
char ch=word[i];
TrieNode *node=current->children[ch];
if(!node)
{
node=new TrieNode();
current->children[word[i]]=node;
}
current=node;
current->prefixes++;
}
current->endofword=true;
}
bool search(TrieNode *root,string word)
{
TrieNode *current=root;
for(int i=0;i<word.size();i++)
{
char ch=word[i];
TrieNode *node=current->children[ch];
if(!node)
return false;
current=node;
}
return current->endofword;
}
int count_prefix(TrieNode *root,string word)
{
TrieNode *current=root;
for(int i=0;i<word.size();i++)
{
char ch=word[i];
TrieNode *node=current->children[ch];
if(!node)
{
return 0;
}
current=node;
}
return current->prefixes;
}
int main()
{
TrieNode *root=new TrieNode();
insert(root,"harshita");
insert(root,"harsh");
insert(root,"sharma");
insert(root,"harry");
string p;
cout<<"Enter the prefix :";
cin>>p;
cout<<count_prefix(root,p)<<endl;
return 0;
}
@dbarnwal
Copy link

Could you please give the code for DFS/BFS implementation using the map.
thank you in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment