c - 二叉搜索树插入错误

标签 c data-structures 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

关于c - 二叉搜索树插入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30412879/

相关文章:

c - `"<program> "would like to access files in your Documents folder` 带有 VS Code 和 macOS Catalina 的消息

c - 推送操作中对数组的堆栈操作错误

c++ - 存储网格的数据结构(将具有负索引)

c - 如何在 C 中的同一个 ADT 中使用多种数据类型?

binary-tree - 二叉树结构

c++ - 二叉搜索树(插入时如何检查是否内存不足)

c - While 循环条件不满足

c - Bubblesort 忽略最后一个元素

c - 行列式程序无法正常工作

java - 如何为二叉搜索树中存储的字符串编写查找前缀和查找单词方法?