繁体   English   中英

在二叉搜索树中插入错误

[英]Error in insertion in binary search tree

我的代码是在二进制搜索树中插入元素,但是在插入第一个元素之后,程序停止运行并且不再执行

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

//全局根变量

bst *root; 

//插入函数

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;
 }
}

//使用预遍历显示函数

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;
}

在您的情况下,您需要一个节点,在该节点下方需要插入新节点。 在您需要检查新节点插入位置的情况下:

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
  }

您可以存储前一个指针,然后在后续步骤中使用它。

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
      }

现在,在随后的代码中使用prev_ptr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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