#include<stdio.h>
#include<stdlib.h>
struct node{ // here we are creating the structure of owr binary tree
struct node *leftNode;
int val;
struct node *rightNode;
}; // end of the struct
struct node *head = 0;
void display(struct node *root);
void CreateTree(struct node *root,struct node *new); // creating the function for creating the tree
int main() // start of the main method
{
int a;
char wish;
struct node *val;
val=(struct node*)malloc(sizeof(struct node));
do{
printf(" enter the number that you want to insert ");
scanf("%d",&a);
val->val = a;
val->rightNode = NULL;
val-> leftNode = NULL;
if(head == 0){
head = val;
}
else {
CreateTree(head,val);
}
printf(" do you want to continue in this [y/n]");
scanf("%s",&wish);
}while (wish != 'n');
printf(" do you want to display your list [y/n]");
scanf("%s",&wish);
if (wish == 'y'){
display(head);
}
printf(" end of the programe \n ");
return 0;
}
void CreateTree(struct node *root,struct node *new){
if (new->val <= root->val){
if(root->leftNode != NULL){
CreateTree(root->leftNode,new);
}
else
root->leftNode = new;
}
if (new->val > root->val){
if(root->rightNode != NULL){
CreateTree(root->rightNode,new);
}
else
root->rightNode = new;
}
}
void display(struct node *current){
if(current->leftNode != NULL)
display(current->leftNode);
printf("%d",current->val);
if(current->rightNode != NULL)
display(current->rightNode);
}
我在二叉树中输入数字,但是当我输入yes作为显示时,它会说 - &gt; “段错误(代码转储)” 这是输出 - |
输入要插入的数字5 你想继续这个[y / n] y 输入要插入的数字4 你想继续这个[y / n] y 输入要插入的数字6 你想继续这个[y / n] n吗? 要显示列表[y / n] y吗? 分段错误(核心转储)
我已经看到了与此相关的其他问题的答案,但我没有得到答案所以请帮我解决这个问题
答案 0 :(得分:0)
在do-while循环中添加val = (struct node*)malloc(sizeof(struct node));
。此外,不要忘记释放你的记忆