我的代码是在二叉搜索树中插入元素,但在插入第一个元素后程序停止运行并且不再执行
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/