DJWright97
DJWright97

Reputation: 13

C++ Segmentation fault BST

I'm currently working on a c++ implementation of a binary search tree. Everything seems to be working perfectly, but my search function is giving me issues.

BinarySearchTree::node* BinarySearchTree::SEARCH(node* x, int key)
{
    if(root == NULL) {
            cout << "This is an empty tree." << endl;
            return NULL;

    } else {
            if(x->key == key) {
                    return x;
            }
            if(x == NULL) {
                    cout << "Value not in tree." << endl;
                    return x;
            }
            if(key < x->key ) {
                    return SEARCH(x->left, key);
            } else {
                    return SEARCH(x->right, key);
            }
    }
}

This gives me a segmentation fault every time I search for a key value that is not in the tree, and when the node value is NULL (such as a value that would be either the max or min if it were included).

Upvotes: 0

Views: 52

Answers (1)

Jerry Chou
Jerry Chou

Reputation: 302

Check NULL pointer first and then the rest. If x is NULL, accessing key by x->key will give you segmentation fault.

if(x == NULL) {
  cout << "Value not in tree." << endl;
  return x;
}
if(x->key == key) {
  return x;
}
...

Upvotes: 0

Related Questions