二叉搜索树:
若一个结点不为空且有左孩子或右孩子,则结点的左孩子的权值小于结点,结点的右孩子的权值大于结点,且对于结点的左右孩子该准则同样成立。
#include<iostream>
#include<cstdio>
using namespace std;
typedef struct Tree{
int num;
struct Tree *left,*right;
}Tree,*PTree;
PTree Create(PTree &pt,int x){
if(!pt){
pt=new Tree;
pt->num=x; pt->left=pt->right=NULL;
}
else{
if(x>pt->num) pt->right=Create(pt->right,x);
else pt->left=Create(pt->left,x);
}
return pt;
}
PTree Insert(PTree &pt,int x){
if(!pt){
pt=new Tree;
pt->num=x; pt->left=NULL; pt->right=NULL;
}
else{
if(x>pt->num) pt->right=Insert(pt->right,x);
else pt->left=Insert(pt->left,x);
}
return pt;
}
PTree FindMin(PTree pt){
if(pt){
while(pt->left){
pt=pt->left;
}
return pt;
}
}
PTree Delete(PTree &pt,int x){
if(!pt) printf("ц╩сп\n");
else if(pt->num>x)
pt->left=Delete(pt->left,x);
else if(pt->num<x)
pt->right=Delete(pt->right,x);
else{
if(pt->left&&pt->right){
PTree tmp=FindMin(pt->right);
pt->num=tmp->num;
pt->right=Delete(pt->right,tmp->num);
}else{
PTree tmp=pt;
if(!pt->left) pt=pt->right;
else pt=pt->left;
delete tmp;
}
}
return pt;
}
void Show(PTree pt){
if(pt){
int x=pt->num;
Show(pt->left);
printf("%d ",x);
Show(pt->right);
}
}
int main(){
int n,x,a;
while(scanf("%d",&n)&&n){
PTree pt=NULL;
for(int i=0;i<n;i++){
scanf("%d",&x);
Insert(pt,x);
}
Show(pt); printf("\n");
printf("Delete: "); scanf("%d",&x);
Delete(pt,x); printf("\n");
Show(pt); printf("\n");
}
}