简体   繁体   中英

Error in insertion in binary search tree

My code is insert elements in binary search tree but after inserting first element the program is stop running and is not executing further

 typedef struct BST
 {
   int info;
   struct BST * left;
   struct BST *right;
 }
bst;

//Global root variable

bst *root; 

//Insert function

void insert(int x) //x is the elemnent to be inserted
{
bst *ptr,*ptr1;
ptr=(bst*)malloc(sizeof(bst));
if(root==NULL) //checking whether the tree is empty or not
  {
  ptr->left=ptr->right=NULL;
  root=ptr;
  }
else
  {
  ptr1=root;
while(ptr1!=NULL)
  {
  if(x>ptr1->info)   //traversing to right if element is greater than  element present
    ptr1=ptr1->right;
  else
    ptr1=ptr1->left; //traversing to left if element is present than the the element
  }
 }
if(x>ptr1->info)
 {
  ptr1->right=ptr;
  ptr->info=x;
 }
else
 {
  ptr1->left=ptr;
  ptr->info=x;
 }
}

//show function using preorder traversal

void preorder(bst *root)
{
 bst *ptr=root;
 printf("%d",ptr->info);
 preorder(ptr->left);
 preorder(ptr->right);
}

int main()
{
int n,x,i;
puts("Enter number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
  {
  puts("Enter elements");
  scanf("%d",&x);
  insert(x);
}
preorder(root);
return 0;
}

In your case, you need the node, below which the new node needs to be inserted. In your case when you are checking for the location where the new node needs to be inserted:

while(ptr1!=NULL)
  {
  if(x>ptr1->info)   //traversing to right if element is greater than  element present
    ptr1=ptr1->right;
  else
    ptr1=ptr1->left; //traversing to left if element is present than the the element
  }

You can store the previous pointer and then use that in the subsequent steps.

ptr1= root;
prev_ptr = NULL;
while(ptr1!=NULL)
      {
      prev_ptr = ptr;
      if(x>ptr1->info)   //traversing to right if element is greater than  element present  
        ptr1=ptr1->right;
      else
        ptr1=ptr1->left; //traversing to left if element is present than the the element
      }

Now use prev_ptr in the subsequent code that you have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM