代码调试成功后发现删除函数无法被正常调用,只能删除30以上的数字,以下是代码:
#include
#define NULL 0
#define SUCC 1
#define NOTFOUND 0
using namespace std;
typedef struct tree
{
int data;
struct tree *lson, *Rson;
}tree , *Bptr;
void insert(int x,Bptr &p)
{
if(p==NULL)
{
p=new tree;
p->data=x;
p->lson=p->Rson=NULL;
return;
}
if(x<=p->data)insert(x,p->lson);
else insert(x,p->Rson);
}
Bptr creat() //创建树
{
Bptr root;int x;
root=NULL;
cin>>x;
while(x!=0)
{
insert(x,root);
cin>>x;
}
return root;
}
int deleteT(int x,Bptr root)
{
Bptr f,p,q,s,r;
p=NULL;
f=root;
q=root->Rson;
while(q!=NULL)
if(x==q->data){p=q;q=NULL;}
else
if(xdata){f=q;q=q->lson;}
else{f=q;q=q->Rson;}
if(p==NULL)return NOTFOUND;
if(p->Rson==NULL)
if(p==f->lson){f->lson=p->lson;delete p;}
else{f->Rson=p->lson;delete p;}
else
if(p->lson==NULL)
if(p==f->lson){f->lson=p->Rson;delete p;}
else{f->Rson=p->Rson;delete p;}
else
{
s=p->lson;
if(s->Rson==NULL)
{
p->data=s->data;
p->lson=s->lson;
delete s;
}
else
{
r=s->Rson;
while(r->Rson!=NULL){s=r;r=r->Rson;}
p->data=r->data;
s->Rson=r->lson;
delete r;
}
}
return SUCC;
}
Bptr search(int x,Bptr p)
{
if(p==NULL)return NOTFOUND;
if(x==p->data)return p;
if(xdata)
return search(x,p->lson);
else return search(x,p->Rson);
}
void inorder(Bptr p)
{
if(p==NULL)return ;
inorder(p->lson);
cout<data<<','<
inorder(p->Rson);
}
int main()
{
Bptr root;int x;
cout<<"请创建一个树:"<
root=creat();
cout
inorder(root);
cout
cin>>x;
deleteT(x,root);
cout<<"中序遍历为;"<
inorder(root);
int y;
cout
cin>>y;
insert(y,root);
cout<<"中序遍历为;"<
inorder(root);
int u;
cout
cin>>u;
if(search(u,root)==0)cout<<"查找失败";
else cout<<"查找成功";
cout<<"中序遍历为;"<<endl;
inorder(root);
system("pause");
return 0;
}