I am new at programming. I am trying to implement Trie dataStructure. But there is segmentation fault whenever i try to insert a string into trie.
Here is the Node class
class Node{
public:
Node *key[2];
Node *parent;
bool EOW;
Node1(){
this->key[0]=NULL;
this->key[1]=NULL;
this->parent = NULL;
this->EOW = false;
}
};
and this is the trie class
class Trie{
public:
Node *root;
Trie(){
root = new Node();
}
void insertUtil(Node *root, char a[]);
void insert(char a[]){
// cout << root <<endl;
// cout << root->key[0];
insertUtil(root, a);
}
};
and this is the insertUtil function
void Trie::insertUtil(Node *root, char a[]){
Node *temp = root;
for(int idx=0;idx<5;idx++){
cout << idx <<endl;
int tmp_chr = a[idx]-'0';
if(!(temp->key[1])){
temp->key[a[idx]-'0'] = new Node();
temp->key[a[idx]-'0']->parent = temp;
}
temp = temp->key[a[idx]-'0'];
}
temp->EOW = -1;
}
int main(){
Trie t1;
char b[5];
cin >> b;
t1.insert(b);
cout << '*';
cin >> b;
t1.insert(b);
cin >> b;
t1.insert(b);
cin >> b;
t1.insert(b);
}
The member key
of Node
is declared as
Node *key[2];
So it's an array of two pointers and given this line in Trie::insertUtil
,
int tmp_chr = a[idx]-'0'; // A variable ignored in the following code, BTW.
I'll assume that the "strings" that the OP is trying to insert are composed only by the characters '0'
and '1'
.
Note that, in the posted code, the null-terminator needed in the used C-string is simply ignored, which is an error by itself, easily fixed by using a proper std::string
instead.
The other issue is in the same loop:
for(int idx = 0; idx < 5; idx++)
{ // ^^^^^^^ It should stop before the null-terminator
// (...)
int tmp_chr = a[idx]-'0'; // Are you sure that there are only '0' or '1'?
if( !(temp->key[1]) )
{ // ^^^ 1 is wrong, here, it should be temp->key[tmp_chr]
temp->key[a[idx]-'0'] = new Node();
// ^^^^^^^^^^ Why not use tmp_chr here and in the following?
// ...
}
// ...
}