#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
int date;
struct node *lchild,*rchild;
}BStree;
void Insert(BStree **bst,int key)
{
BStree *s;
if(*bst==NULL)
{
s=(BStree *)malloc(sizeof(BStree));
s->date=key;
s->lchild=NULL;
s->rchild=NULL;
*bst=s;
}
else if(key<(*bst)->date)
{
Insert(&((*bst)->lchild),key);
}
else if(key>(*bst)->date)
{
Insert(&((*bst)->rchild),key);
}
}
void CreateBStree(BStree **bst)
{
int key;
*bst=NULL;
while(cin>>key&&key)
{
Insert(bst,key);
}
}
void Inorder(BStree *bst)
{
if(bst!=NULL)
{
Inorder(bst->lchild);
cout<<bst->date<<" ";
Inorder(bst->rchild);
}
}
BStree *Search(BStree *bst,int key)//递归方式
{
if(bst==NULL) return NULL;
else if(key==bst->date) return bst;
else if(key<bst->date) return Search(bst->lchild,key);
else if(key>bst->date) return Search(bst->rchild,key);
}
BStree *Search1(BStree *bst,int key)//非递归方式
{
BStree *t;
t=bst;
while(t)
{
if(key==t->date) return t;
else if(key<t->date) t=t->lchild;
else if(key>t->date) t=t->rchild;
}
return NULL;
}
void Delete(BStree *bst,int key)
{
BStree *p,*f,*q,*s;
p=bst;//p为要删除的节点
f=NULL;//f为p的父节点
while(p)//找到key的位置(即p的位置)
{
if(key==p->date) break;
f=p;
if(key<p->date) p=p->lchild;
else if(key>p->date) p=p->rchild;
}
if(p==NULL) return;//判断空树
if(p->lchild==NULL)
{
if(f==NULL) p=p->rchild;
else if(f->lchild==p) f->lchild=p->rchild;
else if(f->rchild==p) f->rchild=p->rchild;
free(p);
}
else
{
q=p;s=p->lchild;
while(s->rchild)
{
q=p;
s=s->rchild;
}
if(q==p) p->lchild=s->lchild;//如果p的左孩子没有右孩子,则直接把p的左孩子往上移
else q->rchild=s->lchild;
p->date=s->date;
free(s);
}
}
void menu()
{
cout<<"------------------------------"<<endl;
cout<<"1-----------------Create BStree"<<endl;
cout<<"2-----------------Insert element"<<endl;
cout<<"3-----------------Inorder tree"<<endl;
cout<<"4-----------------Search element"<<endl;
cout<<"5-----------------delete element"<<endl;
cout<<"0-----------------Exit"<<endl;
cout<<"Input sequence number corresponding function ";
}
int main()
{
std::ios::sync_with_stdio(false);
BStree *bst;
bst=(BStree *)malloc(sizeof(BStree));
int chosen;
menu();
cin>>chosen;
while(1)
{
int key;
switch(chosen)
{
case 1:
cout<<"Enter the element to create the tree(input 0 end) ";
CreateBStree(&bst);
break;
case 2:
cout<<"Enter the element to be inserted(input 0 ends) ";
while(cin>>key&&key)
{
Insert(&bst,key);
}
break;
case 3:
cout<<"The middle sequence is ";
Inorder(bst);
cout<<endl;
break;
case 4:
cout<<"Enter the element you are looking for ";
cin>>key;
BStree *ans;
ans=Search1(bst,key);
if(ans==NULL) cout<<"NO"<<endl;
else cout<<ans->date<<endl;
break;
case 5:
cout<<"Enter the deleted element ";
cin>>key;
Delete(bst,key);
break;
case 0:
break;
}
if(chosen==0) break;
menu();
cin>>chosen;
}
Inorder(bst);
cout<<endl;
return 0;
}