Tries in C++
Implement insert and contains for Tries data structure
Use Data structure:
std::map<char, TNode*> map;
1. Insert
2. Contains
3. AutoComplete
4. File: $b/cpp/Tries/cpptries/main.cpp
class TNode{
public:
bool terminal;
std::map<char, TNode*> map;
public:
TNode(bool t){
terminal = t;
}
};
class Tries{
public:
TNode* root;
public:
Tries(){
root = new TNode(true);
}
};
void insert(TNode* root, std::string str, int i){
if(i < str.size()){
if(i == str.size() - 1){
if(root->map[str[i]] != NULL)
root->map[str[i]]->terminal = true;
else
root->map[str[i]] = new TNode(true);
}else{
if(root->map[str[i]] == NULL)
root->map[str[i]] = new TNode(false);
insert(root->map[str[i]], str, i+1);
}
}
}
bool contains(TNode* root, std::string str, int i){
if(root){
if(str.size() == 0)
return root->terminal;
if(i == str.size() - 1){
if(root->map[str[i]] != NULL)
return root->map[str[i]]->terminal;
else
return false;
}else{
return contains(root->map[str[i]], str, i+1);
}
}else{
return false;
}
}
TNode* autoComplete(TNode* root, std::string str, int i){
if(root){
if(i < str.length()){
TNode* node = root -> map[str[i]];
return autoComplete(node, str, i+1);
}else{
if(root -> map.size() > 0){
return root;
}
}
}
return NULL;
}
void getList(TNode* root, std::string str){
if(root){
if(root -> map.size() > 0){
std::map::iterator it = root -> map.begin();
while(it != root -> map.end()){
// [it -> first , it -> second]
getList(it -> second, str + it -> first);
it++;
}
}else{
printf("str=%s\n", str.c_str());
}
}
}