0
votes

I tried to implement BST as follows .Created structure as NODE.it has two pointers left and right and one integer value (data).

#include<iostream>
#include<stdio.h>
 using namespace std;
struct node
{
struct node*left;
struct node*right;
int data;

};
    node* head1;  
    int bol=0;

void insert1(int x)  
 {


node* nodes=new node;
nodes->left=NULL;
nodes->right=NULL;
nodes->data=x;

    if(bol==0)
    {
    head1=nodes;
      bol=1;
    }
  else
{
     node* ptr=head1;
while(ptr!=NULL) 
 {

 if(x<=ptr->data)
{
    ptr=ptr->left;

}
else
    {

    ptr=ptr->right;

    }

 }
  ptr=nodes;

 }
  }





int main() 
{




int n,m;
 cout<<"Enter the size of first BST"<<endl;
cin>>n;


 int arrayfirst[n];

for(int i=0;i<n;i++)
{
cin>>arrayfirst[i];
insert1(arrayfirst[i]);

} 

 cout<<head1->data<<endl;
 cout<<head1->left->data<<endl;
 //printPreorder(head1);

   }

but error is showed if i try to print the data of next node to head.

Thanks in advance

1
When you used the debugger, were the values in the pointers correct? - Thomas Matthews
You are setting ptr = nodes, but you should actually set the parent's left or right to nodes. Setting ptr to nodes does not change the parent's left or right pointers. - user1952500

1 Answers

0
votes

You are setting ptr = nodes, but you should actually set the parent's left or right to nodes. Setting ptr to nodes does not change the parent's left or right pointers.

So do something like:

{
    node* ptr=head1;
    node *parent = NULL;
    while(ptr != NULL) {
        parent = ptr;
        if(x <= ptr->data) {
            ptr = ptr->left;
        }
        else {
            ptr = ptr->right;
        }
    }
    if (parent != NULL) { // this should always be true
        if (parent->left == ptr) {
            parent->left = nodes;
        } else {
            parent->right = nodes;
        }
    }
}

Note: the above code is not tested but describes the approach.