二叉排序树 (创建+插入+删除)

二叉排序树 (创建+插入+删除)




#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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值