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];
            }
};

In looking at your code, it appears to me, that if p is NULL then there are no members and an error will result. I'm thinking that in the while statement, checking if size != 0 would work better.

On a side note having different nodes in the tree with the same key won't work very well. You would probably be better off using a hash function as the key.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.