#include<iostream.h>
struct BiNode
{
int info;
BiNode *lc,*rc;
};
class BiSortTree
{
public:
BiNode*GreateBiSortTree(int a[],int n);
~BiSortTree(){ root=NULL;};
BiNode* InsertBST(BiNode *&root ,BiNode *pNode);
void DeleteBST(BiNode *p,BiNode *&f);
BiNode* DeleteKey(BiNode*&root,int key);
BiNode *SearchBST(BiNode *root,int k);
BiNode* SearchFather(BiNode* root ,int key,int &sonNo);
void Print (BiNode *root);
public :
BiNode *root;
};
void BiSortTree::Print(BiNode *root)
{
BiNode *p;
p=root;
if(p!=NULL){
Print(p->lc);
cout<<p->info<<" ";
Print(p->rc);
}
}
BiNode*BiSortTree::DeleteKey(BiNode *&root,int key)
{
BiNode *p,*f;
int sonNO;
p=NULL;
if (key==root->info ){
f=root;
DeleteBST(root,p);
root=p;
return f;
}
p=SearchFather(root,key,sonNO);
if (p=NULL&&sonNO!=0)return NULL;
if (sonNO==1)
{
DeleteBST(p->lc ,p);
return p->lc ;
}
else{
DeleteBST(p->rc ,p);
return p->rc ;
}
cout<<"删除"<<key<<"后的二叉排序树是:";
Print(root);
}
void BiSortTree::DeleteBST(BiNode *p,BiNode *&f)
{
BiNode *q,*r;
if ((p->lc==NULL)&&(p->rc==NULL))
p=NULL;
else if(p->rc ==NULL)
{
if (f==NULL)f=p->lc ;
else f->lc=p->lc ;
}
else if (p->lc ==NULL){
if (f=NULL)f=p->rc;
else f->rc=p->rc ;
}
else
{
q=p->lc;
r=p;
while(q->rc !=NULL){
r=q;
q=q->rc;
}
if (r!=p) r->rc =q->lc ;
if(r!=p) q->lc=p->lc ;
q->rc=p->rc ;
if (f==NULL)f=q;
else
if (f->lc ==p) f->lc =q;
else f->rc=q;
}
}
BiNode* BiSortTree::SearchFather (BiNode*root,int key,int &sonNo)
{
BiNode *p,*q;
sonNo=0;
q=NULL;
p=root;
if (key==p->info)return NULL;
while(p!=NULL)
{
if (key==p->info)
return q;
q=p;
if (key<p->info ){p=p->lc ;sonNo=1;}
else {p=p->rc;sonNo=2;}
}
if (key<q->info) sonNo=-1;
else sonNo=-2;
return q;
}
BiNode*BiSortTree::GreateBiSortTree (int a[],int n )
{
int k;
BiNode *root,*p;
root=NULL;
for(k=0;k<n;k++)
{
p=new BiNode;
p->info=a[k];
InsertBST(root ,p);
}
cout<<"二叉排序树为:";
Print (root);
return root;
}
BiNode* BiSortTree::InsertBST(BiNode *&root ,BiNode *pNode)
{
BiNode *p;
int sonNo;
pNode->lc=NULL;
pNode->rc=NULL;
if (root==NULL){root=pNode;return NULL;}
p=SearchFather(root,pNode->info,sonNo);
if (sonNo>0)return NULL;
if (sonNo==-2)p->rc=pNode;
else p->lc=pNode;
return p;
}
void main()
{
int n,key;
cout<<"请输入二叉树的节点数目:";
cin>>n;
int a[10];
cout<<"请依次输入需排序的数:";
for(int i=0;i<n;i++){
cin>>key;
a[i]=key;
}
int m;
BiSortTree G;
//BiNode *p;
G.GreateBiSortTree(a,n);
cout<<"请输入需要删除的节点的值:";
cin>>m;
G.DeleteKey(G.root,key);
}