我需要使用 c 创建一个程序(使用二叉树)这个程序需要保存学生的姓名和 id,并允许您按前序、按序和后序插入、删除、搜索和显示名称,我编写了代码,但它没有'不起作用,插入有问题,它只需要 id,它不带名称,我想知道这段代码有什么问题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct bin_tree
{
int data;
char name[100];
struct bin_tree * right, * left;
};
typedef struct bin_tree node;
void insert(node ** tree, int val, char word[100])
{
node *temp = NULL;
if(!(*tree))
{
temp = (node *)malloc(sizeof(node));
temp->left = temp->right = NULL;
temp->data = val;
temp->data = word;
*tree = temp;
return;
}
if(val < (*tree)->data)
{
insert(&(*tree)->left, val,word);
}
else if(val > (*tree)->data)
{
insert(&(*tree)->right, val,word);
}
}
struct tree *delet(struct bin_tree *ptr,int x)
{
struct bin_tree *p1,*p2;
if(!ptr)
{
printf("\n student not found ");
return(ptr);
}
else
{
if(ptr->data < x)
{
ptr->right = delet(ptr->right,x);
}
else if (ptr->data >x)
{
ptr->left=delet(ptr->left,x);
return ptr;
}
else
{
if(ptr->data == x)
{
if(ptr->left == ptr->right)
{
free(ptr);
return(NULL);
}
else if(ptr->left==NULL)
{
p1=ptr->right;
free(ptr);
return p1;
}
else if(ptr->right==NULL)
{
p1=ptr->left;
free(ptr);
return p1;
}
else
{
p1=ptr->right;
p2=ptr->right;
while(p1->left != NULL)
p1=p1->left;
p1->left=ptr->left;
free(ptr);
return p2;
}
}
}
}
return(ptr);
}
node* search(node ** tree, int val)
{
if(!(*tree))
{
return NULL;
}
if(val < (*tree)->data)
{
search(&((*tree)->left), val);
}
else if(val > (*tree)->data)
{
search(&((*tree)->right), val);
}
else if(val == (*tree)->data)
{
return *tree;
}
}
void print_preorder(node * tree)
{
if (tree)
{
printf("%d\n%s\n",tree->data,tree->name);
print_preorder(tree->left);
print_preorder(tree->right);
}
}
void print_inorder(node * tree)
{
if (tree)
{
print_inorder(tree->left);
printf("%d\n%s\n",tree->data,tree->name);
print_inorder(tree->right);
}
}
void print_postorder(node * tree)
{
if (tree)
{
print_postorder(tree->left);
print_postorder(tree->right);
printf("%d\n%s\n",tree->data,tree->name);
}
}
void main()
{
node *root;
node *tmp;
int a,item_no,z,i=0;
char x,b[100],c;
root=NULL;
while(x!='5')
{
printf("\nmenu\n----\n1. insert\n2. delete\n3. search\n4. display\n5. end program \n\n");
printf("\nEnter the choice:");
scanf("%s",&x);
switch(x)
{
case '1':
{
printf("\nEnter the id: ");
scanf("%d",&a);
printf("\nenter the name: ");
while ( ( c = getchar() ) != '\n' && i < 100 )
{
b[ i++ ] = c;
}
b[ i ] = '\0';
insert(&root,a,b[100]);
break;
}
case '2':
{
printf("\n Enter the student id to be deleted : ");
scanf(" %d",&item_no);
root=delet(root,item_no);
break;
}
case '3':
{
printf("\nEnter student id: ");
scanf("%d",&z);
tmp = search(&root, z);
if (tmp)
{
printf("\nstudent id=%d\nstudent name: %s\n", tmp->data,tmp->name);
}
else
{
printf("\nData Not found.\n");
}
}
case '4':
{
printf("Pre Order Display\n");
print_preorder(root);
printf("In Order Display\n");
print_inorder(root);
printf("Post Order Display\n");
print_postorder(root);
}
case '\t':
case '\n':
case ' ':
default :{
printf("\nwrong entery!\n");
break;
}
}
}
return 0;
}
}