二叉排序树 (创建+插入+删除)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int Data;
struct Node *LChild;
struct Node *RChild;
int Ltag;
int Rtag;
}BSTNode,*PBSTNode;
void InsertBST(PBSTNode *bt,int key) //二叉排序树的插入
{
PBSTNode s;
if(key==-1)
return; //反正NULL已经赋了,见到-1就return,其实-1不写,代码也可正常运行
if(*bt==NULL)
{
s=(PBSTNode)malloc(sizeof(BSTNode));
s->Data=key;
s->LChild=NULL;
s->RChild=NULL;
*bt=s;
}
else if(key<(*bt)->Data)
InsertBST(&((*bt)->LChild),key);
else if(key>(*bt)->Data)
InsertBST(&((*bt)->RChild),key);
return;
}
void DeleteBST(PBSTNode *bt,int key) //二叉排序树的删除
{
PBSTNode p,f,s,q;
p=(*bt);f=NULL;
while(p)
{
if(p->Data==key)
break;
f=p;
if(p->Data>key)
p=p->LChild;
else
p=p->RChild;
}
if(p==NULL)
return ;
if(p->LChild==NULL)
{
if(f==NULL)
(*bt)=p->LChild;
else if(f->LChild==p)
f->LChild=p->RChild;
else
f->RChild=p->RChild;
free(p);
}
else
{
q=p;s=p->LChild;
while(s->RChild)
{
q=s;s=s->RChild;
}
if(q==p)
q->LChild=s->LChild;
else
q->RChild=s->LChild;
p->Data=s->Data;
free(s);
}
return;
}
void CreateBST(PBSTNode *bt) //二叉排序树的创建
{
int key;
char str;
(*bt)=NULL;
do
{
scanf("%d%c",&key,&str);
InsertBST(bt,key);
}
while(str!='\n');
}
int a,b,c,d;
void InPrint2(PBSTNode bt) //中序遍历输出
{
if(bt!=NULL)
{
InPrint2(bt->LChild);
if((bt->Data>a)&&((bt->Data)<b))
printf("%d ",bt->Data);
InPrint2(bt->RChild);
}
}
PBSTNode pre=NULL;
void PostThread(PBSTNode* bt) //后序线索化
{
if((*bt)!=NULL)
{
PostThread(&(*bt) ->LChild);
PostThread(&(*bt) ->RChild); //回溯后,bt就是右子树的根节点
if ((*bt)->LChild == NULL) //if没什么用,但if引出的括号有用
{
(*bt)->LChild = pre;
(*bt)->Ltag = 1;
}
if (pre!=NULL&&pre->RChild==NULL) //这个
{
pre->RChild=*bt;
pre->Rtag=1;
}
pre=(*bt);
}
}
void InPrint(PBSTNode bt) //中序遍历输出
{
if(bt!=NULL)
{
InPrint(bt->LChild);
printf("%d ",bt->Data);
InPrint(bt->RChild);
}
}
int main()
{
PBSTNode bt;
CreateBST(&bt);
scanf("%d %d",&a,&b);
scanf("%d",&c);
scanf("%d",&d);
InPrint2(bt);
printf("\n");
InsertBST(&bt,c);
InPrint(bt);
printf("\n");
DeleteBST(&bt,c);
DeleteBST(&bt,d);
InPrint(bt);
printf("\n");
return 0;
}