#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define num 4
struct tree
{
char name[20];
char city[20];
char sex[10];
char age[10];
char job[10];
struct tree *left;
struct tree *right;
};
struct tree data[num]=
{
"willing","Tianjing","Female","21","worker",NULL,NULL,
"tom","Beijing","Male","31","doctor",NULL,NULL,
"sun","Weifang","Male","24","student",NULL,NULL,
"marry","Shanghai","Female","19","techer",NULL,NULL
};
struct tree *construct(struct tree *root,struct tree *r,struct tree *data)
{
struct tree *p;
if(!r)
{
r=(struct tree *)malloc(sizeof(struct tree));
if(!r)
{
printf("memory error!!\n");
exit(0);
}
r->left=NULL;
r->right=NULL;
strcpy(r->name,data->name);
strcpy(r->city,data->city);
strcpy(r->sex,data->sex);
strcpy(r->age,data->age);
strcpy(r->job,data->job);
if(!root)
return r;
if(strcmp(data->name,root->name)<0)
root->left=r;
else
root->right=r;
return r;
}
if(strcmp(data->name,root->name)<0)
construct(r,r->left,data);
else
construct(r,r->right,data);
return root;
}
struct tree *search(struct tree *root,char name[])
{
struct tree *p;
p=root;
while(strcmp(p->name,name)!=0)
{
if(strcmp(name,p->name)<0)
p=p->left;
else
p=p->right;
if(p==NULL)
break;
}
return(p);
}
void print(struct tree *root)
{
if(!root)
return;
print(root->left);
printf("%s\n",root->name);
print(root->right);
}
void print_current(struct tree *r)
{
if(!r)
return;
printf("%s\n",r->name);
printf("%s\n",r->city);
printf("%s\n",r->sex);
printf("%s\n",r->age);
printf("%s\n",r->job);
}
int main()
{
int i;
char name[30],c[10],swap[30];
struct tree *root,*p,*temp;
root=NULL;
p=NULL;
temp=NULL;
for(i=0;i<num;i++)
root=construct(root,root,&data[i]);
printf("all staffs!!\n");
print(root);
printf("input name!!\n");
scanf("%s",name);
p=search(root,name);
if(!p)
{
printf("can not find it!!\n");
printf("insert it??[y/n]");
scanf("%s",c);
if(strcmp(c,"y")==0)
{
temp=(struct tree *)malloc(sizeof(struct tree));
if(!temp)
{
printf("memory error!!\n");
exit(0);
}
printf("input name!\n");
scanf("%s",swap);
strcpy(temp->name,swap);
printf("input city!\n");
scanf("%s",swap);
strcpy(temp->city,swap);
printf("input sex!\n");
scanf("%s",swap);
strcpy(temp->sex,swap);
printf("input age!\n");
scanf("%s",swap);
strcpy(temp->age,swap);
printf("input job!\n");
scanf("%s",swap);
strcpy(temp->job,swap);
temp->left=NULL;
temp->right=NULL;
root=construct(root,root,temp);
printf("all staffs now!!\n");
print(root);
}
return 0;
}
print_current(p);
return 1;
}