Search code examples
c++algorithmbinary-search-tree

Binary search tree algorithm crashing when passing a parameter that isn't in the tree to the search function


i tried building a binary search tree, everything worked fine when i gave it parameters that were in in the tree, but i wanted to see if it would print 0 when it couldn't find the int in the tree instead when i call search it's crashing.

i tried adding a condition after the first if statement but that ruined the recursion here's the code:

   struct node
{
  int data;
  node* left;
  node* right;
  
  node(int d)
  {
    data = d; 
    left = right = NULL;

  }

};

node* insert(node *root, int n)
{
  if(root == NULL)
  {
    return new node(n);
  }
  else
  {
    node* y;

    if(n <= root->data)
    {
      y = insert(root->left, n);
      root->left = y;
    }
    else
    {
      y = insert(root->right, n);
      root->right = y;
    }

    return root;
  }

}

node* search(node *root,int n)
{
  if(root == NULL || root->data == n)
  {
    return root;
  }
  
  if(root->data < n)
  {
    return search(root->right, n);
  }
  return search(root->left, n);
}

int treemax(node *root)
{
   while(root->right != NULL)
   {
     root = root->right;
   }
   return root->data;
}

int treemin(node *root)
{
  while(root->left != NULL)
  {
    root = root->left;
  }
  return root->data;
}

int main()
{
   node *R = NULL;
   R = insert(R, 33);
   insert(R,12);
   insert(R, 40);
   insert(R, 36);
   insert(R, 21);
  
  
  cout << search(R, 65)->data << endl;
  
  
}
    

Solution

  • When you run

    cout << search(R, 65)->data << endl;
    

    search(R, 65) returns NULL. You can't dereference NULL by doing ->data on it. You probably want:

    Node* result = search(R, 65);
    if (result)
    {
        cout << result->data << endl;
    }
    else
    {
        cout << "Not found" << endl;
    }