二叉排序树
#include <iostream>
using namespace std;
typedef struct
{
int key;
char oi;
}ElemType;
typedef struct BSTNode
{
ElemType data;
//int length;
struct BSTNode *lchild,*rchild;
}BSTNode,*BSTree;
BSTree SearchBST(BSTree T,int key)
{
if(!T || key == T-> data.key){
//cout<<1;
return T;}
else if(key < T-> data.key)
return SearchBST(T-> lchild,key);
else
return SearchBST(T-> rchild,key);
}
void InsertBST(BSTree &T,ElemType E)
{
// cout<<1;
if(!T) //这个地方不能把if的顺序放到后面,我调试了下,貌似是优先判断是否为空,然后在操作......
{
BSTree s;
s = new BSTNode;
s ->data = E;
s -> lchild = s -> rchild = NULL;
T = s;
}
else if(E.key < T-> data.key)
InsertBST(T-> lchild,E);
else if(E.key > T-> data.key)
InsertBST(T-> rchild,E);
// else
// {
// }
}
void CreatBST(BSTree &T)
{
ElemType e;
T = NULL;
cin>>e.key;
while(e.key!=999999)
{
InsertBST(T,e);
cin>>e.key;
}
}
void DeleteBST(BSTree &T,int key)
{
BSTree f=NULL,p=T,s,q;
while(p)
{
if(p->data.key == key)
break;
else if(p->data.key>key)
p = p -> lchild;
else
p = p -> rchild;
}
if(!p) return;
if(p -> lchild && p -> rchild)
{
q = p;
s = p -> lchild;
while(p -> lchild)
{
q = s;
s = s -> rchild;
}
if(q != p)
q -> rchild = s -> rchild;
else
q -> lchild = s -> lchild;
delete s;
return;
}
else if(!p -> rchild)
{
q = p;
p = p ->lchild;
}
else if(!p ->lchild)
{
q = p;
p = p -> rchild;
}
if(!f)
T = p;
else if(q == f ->lchild)
f ->lchild = p;
else
f ->rchild = p;
delete q;
}
int main()
{
int i;
//int k;
BSTree T;
while(true)
{
CreatBST(T);
int x;
printf("请输入一个查找的数!\n");
scanf("%d",&x);
BSTree flag = SearchBST(T,x);
if(flag!=NULL)
printf("查找成功!数值为:%d",flag->data.key);
else
printf("查找失败!");
//printf("%d",SearchBST(T,x));
printf("\n");
}
return 0;
}