I have to write a hangman game in Cpp which choose random words from txt file using binary search tree. Here is the code - compilation is successful, but its not working properly, its crashing. Exception - Segmentation fault: 11 Row - if (el.length() <= p->n.length()) Can someone help me?
class Node
{
public:
Node *a;
Node *b;
string n;
Node(Node *right, Node *left, string str)
{
this->a = right; this->b = left; this->n = str;
}
Node(string str)
{
this->n = str;
}
};
class Tree
{
private:
int size = 0;
vector<string> vecRandom;
public:
Node *root;
Tree()
{
root = NULL;
size = 0;
}
void insert(string &el)
{
Node *p = root, *prev = 0;
while (p != 0)
{
prev = p;
if (el.length() < p->n.length())
{
p = p->a;
}
else
{
p = p->b;
}
}
if (root == 0)
{
root = new Node(el);
vecRandom.push_back(el);
size++;
}
else if (el.length() < prev->n.length())
{
prev->a = new Node(el);
vecRandom.push_back(el);
size++;
}
else
{
prev->b = new Node(el);
vecRandom.push_back(el);
size++;
}
}
string random()
{
srand(time(NULL));
random_shuffle(vecRandom.begin(), vecRandom.end());
return vecRandom[rand()%vecRandom.size()-1];
}
};