Bus error in tree insertion

Hi, I am new to C++ and unix. I am trying to write a programm for inserting elements into a binary tree. To get the code flow I used few Couts and m facing buss error while insertion.
Below is the code snippet. explainations needed. thanks :slight_smile:

#include <iostream.h>
struct mytree
{
  int element;
  mytree * left;
  mytree * right;
}*root;
class tree
{
  public:
  int size(mytree * new_t);
  mytree* insert(int a, mytree * new_t );
};
int tree:: size(mytree * new_tr)
{
  if(new_tr==NULL)
  {
    return (0);
  }
  else
  {
    return ((size(new_tr -> left)) + (size(new_tr -> right)) + 1);
  }
}

///////////////////////////////////////////
mytree* tree::insert(int a, mytree * new_t )
{
  if(new_t == NULL)
  {
    new_t->element = a;
    new_t->right = NULL;
    new_t -> left =NULL;
    cout << "very first insert";
  }
  else
  {
    if (a <= new_t -> element)
    {
      if (new_t -> left != NULL)
      {
        cout <<" first small insert";
        insert(a, new_t->left);
      }
      else
      {
        cout << "first final small insert";
        mytree * node = new mytree;
        new_t -> left = node;
        new_t -> left -> element = a;
        new_t -> left -> left = NULL;
        new_t -> left -> right = NULL;
      }
    }
    if (a > new_t -> element)
    {
      if (new_t -> right != NULL)
      {
        cout << "first greator insert";
        insert(a, new_t -> right);
      }
      else
      {
        mytree * node = new mytree;
        new_t -> right = node;
        new_t -> right -> element = a;
        new_t -> right -> left = NULL;
        new_t -> right -> right = NULL;
        cout << "first greator final insert";
      }
    }
  }
}
int main()
{
  tree * a = new tree;
  int no_add,this_element, sizet;
  char choice;
  this_element=0;
  mytree * tree1 = new mytree;

  cout <<"enter no of elements to be added ";
  cin >> no_add;
  for(int i=0; i < no_add; i++)
  {
    cout << "what to add at element "<< i<< " ? "<<endl ;
    cin >> this_element;
    tree1 = a->insert(this_element, tree1);
  }
  cout << "need to know size ? y or n "<< endl;
  cin >> choice;
  if (choice == 'y')
  {
    sizet = a-> size(tree1);
    cout << " size of tree is " << endl ;
    cout << sizet;
  }
  else
  {
    cout << " program ends here";
  }
  return 0;
}

Is a no return from insert causing problem ? If yes why does it compile

You certainly use insert()'s return value in some places, so probably.

Because the compiler can't read your mind. It objects to faulty syntax, not faulty logic.

1 Like