树的建立,输入,输出,查找,插入,删除。
#include<stdio.h>
#include<stdlib.h>
struct node* Get();
struct node* insert(struct node *t,int m);
struct node* search(struct node* s,int n);
struct node* Delete(struct node* w,int d);
struct node* findmin(struct node* s);
struct node* findmax(struct node* s);
void Put(struct node* s);
struct node{
int n;
struct node* left;
struct node* right;
};
int main()
{
struct node* s;
printf("现在建立并写入树\n");
s=Get();
int a,n;
printf("1:输出\t2:查找\t3:插入\t4:删除\t5:退出\n");
while(1){
printf("请输入您的选择:");
scanf("%d",&a);
switch(a){
case 1:Put(s);
break;
case 2:printf("请输入您要查找的数:");
scanf("%d",&n);
search(s,n);
break;
case 3:printf("请输入您要插入的数:");
scanf("%d",&n);
insert(s,n);
break;
case 4:printf("请输入您要删除的数:");
scanf("%d",&n);
s=Delete(s,n);
break;
case 5:printf("再见!");
break;
}
if(a==5)break;
}
}
struct node* Get(){
int n;
struct node *s=NULL,*p;
printf("请输入以-1结束的一串数:");
scanf("%d",&n);
while(n!=-1){
if(s==NULL){
p=(struct node*)malloc(sizeof(struct node));
p->n=n;
s=p;
s->left=s->right=NULL;
}else
insert(s,n);
scanf("%d",&n);
}
return s;
}
struct node* insert(struct node *t,int m){
if(t==NULL){
t=(struct node*)malloc(sizeof(struct node));
t->n=m;
t->left=NULL;
t->right=NULL;
}else if(m<=t->n){
t->left=insert(t->left,m);
}else if(m>t->n){
t->right=insert(t->right,m);
}
return t;
}
struct node* search(struct node* s,int n){
struct node* t;
t=s;
if(t!=NULL){
if(n>t->n){
t=search(t->right,n);
}else if(n<t->n){
t=search(t->left,n);
}else if(n==t->n){
printf("找到了!,%d位于%p\n",n,t);
return t;
}
}
else
printf("不好意思,没有找到%d呢\n",n);
}
struct node* Delete(struct node* w,int d){
struct node* min;
if(w==NULL){
printf("没有找到%d\n",d);
}else if(d>w->n){
w->right=Delete(w->right,d);
}else if(d<w->n){
w->left=Delete(w->left,d);
}else if(w->left&&w->right){
min=findmin(w->right);
w->n=min->n;
w->right=Delete(w->right,w->n);
}else{
min=w;
if(w->left==NULL){
w=w->right;
}else if(w->right==NULL){
w=w->left;
}
free(min);
}
return w;
}
struct node* findmin(struct node* s){
struct node* min;
min=s;
while(min->left!=NULL){
min=min->left;
}
return min;
}
struct node* findmax(struct node* s){
struct node* max;
max=s;
while(max->right!=NULL){
max=max->right;
}
return max;
}
void Put(struct node* s){
struct node* a;
a=s;
if(a->left!=NULL){
Put(a->left);
}
if(a->left==NULL&&a->right==NULL){
printf("%d ",a->n);
}else
printf("%d ",a->n);
if(a->right!=NULL){
Put(a->right);
}
}