0
votes
struct node
{
   int data;
   node *left,*right;
};

  class bst
 {
 public:
    node *root;
    bst(){root = NULL;}
   void bst_insert(node*,int);
   void inorder(node*);
   };


void bst::bst_insert(node* x, int d) {
   if (x== NULL) {
      node* tmp = new node;
      tmp->data = d;
      tmp->left = NULL;
      tmp->right = NULL;
      x= tmp;
   }
   else if (d <= x->data)
      bst_insert(x->left,d);
   else
      bst_insert(x->right,d);
}

void bst::inorder(node* x) {
   if(x != NULL) {
      inorder(x->left);
      cout << x->data << " ";
      inorder(x->right);
   }
}

int main() {
   bst b;
   b.bst_insert(b.root,3);
   b.bst_insert(b.root,2);
   b.inorder(b.root);
}

bst is a class with member node* root (initialize with null on constructor)

Binary Search Tree display in order always shows empty.

What is wrong with the code ?

the code seems fine, but always bst has no value and always show empty, and root is null !!!

1

1 Answers

0
votes

No code anywhere sets root to anything other than NULL. When you call inorder, it does nothing since root is NULL.

b.bst_insert(b.root,3);

Since root is NULL at first, this is equivalent to:

b.bst_insert(NULL,3);

This doesn't attach the newly-created node to anything.