//二叉排序链表建立
typedef struct{
KeyType key;
char otherinfo;
}ElemType;
typedef struct BSTNode{
ElemType data;
struct BSTNode *lch,*rch;
}BSTNode,*BSTree;
//二叉排序树的插入
BSTree InsertBST(BSTree T,int key){
ElemType e;
e.key=key;
e.otherinfo='f';
if(!T){//如果T为NULL
BSTree S=(BSTree)malloc(sizeof(BSTNode));
S->data=e;
S->lch=S->rch=NULL;//把新结点*S作为叶子结点
T=S; //把新结点*S链接到插入位置T
}
else if(e.key<T->data.key) //如果key<当前值插入左子树
T->lch=InsertBST(T->lch,key);
else if(e.key>T->data.key) //key>当前值则插入右子树
T->rch=InsertBST(T->rch,key);
return T;
}
//二叉树建立
BSTree CreatBST(){
BSTree T=NULL;
int key;
scanf("%d,",&key);
while(key!=-1){ //-1作为结束符
T=InsertBST(T,key);
scanf("%d,",&key);
}
return T;
}
//二叉排序链表的查找 返回key结点
BSTree SearchBSTree(BSTree S,int key){
if((!S)||key==S->data.key) return S;
else if(key>S->data.key) S=SearchBSTree(S->rch,key);
else S=SearchBSTree(S->lch,key);
return S;
}
//删除结点函数
BSTree deleteNode(BSTree T){
BSTree p;
if(T->lch==NULL&&T->rch==NULL){ //叶子结点
p=T;
T=NULL;
free(p);
return T;
}
else if(T->rch==NULL){ //右子树为空
p=T;
T=T->lch;
free(p);
return T;
}
else if(T->lch==NULL){ //左子树为空
p=T;
T=T->rch;
free(p);
return T;
}
else{ //左右子树都不为空
//拿左子树上最大值替换T
BSTree parent=T;
BSTree pre=T->lch;
//左子树最右支就是左子树最大数
while(pre->rch){
parent=pre; //parent保存pre上一个结点
pre=pre->rch;
}
T->data=pre->data; //pre是左支最大值替换T
if(parent!=T){ //如果T有右子树则上while执行parent不等于T
parent->rch=pre->lch; //则把pre左子树接到上级右子树
}
else{ //T 无右支while(pre->rch)未执行
T->lch=pre->lch; //则把左支接上去
}
free(pre);
return T;
}
}
//二叉排序树的删除
BSTree DeleteBST(BSTree T,int key){
//找到这个结点位置
if(!T) return T;
else{
if(T->data.key==key)
T=deleteNode(T);
else if(key>T->data.key)
T->rch=DeleteBST(T->rch,key);
else T->lch=DeleteBST(T->lch,key);
return T;
}
}
//二叉树中序遍历
int InOrder(BSTree T){
if(!T) return 0;
else{
InOrder(T->lch);
printf("%d ",T->data.key);
InOrder(T->rch);
}
}