为什么会出现这样烦人的二叉搜索树 (bst) seg.fault 错误?

why such an annoying binary search tree(bst) seg.fault error?

input no. of elements , elements of binary search tree , input elemt whoose subtree you want to display

#include <stdio.h>

defn of struct node of bst

typedef struct node
{
int info;
struct node *right, *left;
}NODE; 

insert fn , node at leaf

struct node* insertBst(struct node* root, int ele)
{

if(root == NULL)
{
    NODE* temp = (NODE*)malloc(sizeof(NODE));
    temp -> info = ele;
    temp -> right = temp -> left = NULL;
    return root;
}

else if(ele > root -> info)
{
    root -> right = insertBst(root -> right, ele);
}

else if(ele < root -> info)
{
    root -> left = insertBst(root -> left, ele);
}


}

searching for the address of the ele

NODE* search(int ele, NODE* root)
{
if( root == NULL) return NULL;
if(ele > root -> info)
{
    return search(ele, root -> right); 
}

else if( ele < root -> info)
{
    return search(ele, root -> left);
}

else if(ele == root -> info) //ele found
{
    return root;
}

 }

displaying the made bst using pre order : ROOT , LEFT, RIGHT

void preorder(NODE* root)
{
   if(root)
{
    printf("%d ", root -> info);
    preorder(root -> left);
    preorder(root -> right);
 }
}

driver where i call insert to create my bst, node whose subtree im >>displaying

int main()
{
int n, ele; //no. of elements in bst
NODE* root = NULL;
printf("no. of bst elements");
scanf("%d", &n);
printf("elements to be inserted in bst");
for(int i = 0; i < n; ++i)
{
    scanf("%d", &ele);
    NODE* t = insertBst(root, ele);
}

printf("element whose subtree needs to be displayed");
scanf("%d", ele); //elements whose subtree is to be diplayed
NODE *temp;
temp = search(ele, root);
preorder(temp);
}

段错误可能在行中:

scanf("%d", ele);

你应该传递 ele 的地址而不是它的值,就像你在 for 循环中所做的那样。

此外,您的程序将无法运行,因为函数 insertBst 永远不会分配根节点,因为任何时候 if(root == NULL) 为真(总是)您将分配一个节点,但您return 与 root 相同,但仍然是 NULL。你可能是想 return temp.

此外,在取消引用指针之前检查 temp(在 malloc 之后)是一个很好的做法,因为 malloc 可能会失败并且 return NULL,取消引用它会使你的程序崩溃。