二叉排序树的插入和删除(课本函数大杂烩)

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct node
{
    int data;
    struct node*lchild;
    struct node*rchild;
}BiTNode,*BiTree;
void creat(BiTree*root)
{
    int ch;
    scanf("%d",&ch);
    if(ch==-1)
    {
    *root=NULL;
    }
    else
    {
    *root=(BiTree)malloc(sizeof(BiTNode));
    (*root)->data=ch;
    creat(&((*root)->lchild));
    creat(&((*root)->rchild));
    }
}
void search(BiTree root,int a,int b)
{
    if(root!=NULL)
    {
        search(root->lchild,a,b);
        if((root->data>a)&&(root->data<b))
        printf("%d ",root->data);
        search(root->rchild,a,b);
    }
}
void insert(BiTree *root,int c)
{
    BiTree s;
    if(*root==NULL)//递归结束条件
    {
        s=(BiTree)malloc(sizeof(BiTNode));
        s->data=c;
        s->lchild=NULL;
        s->rchild=NULL;
        *root=s;
    }
    else if(c<(*root)->data)
        insert(&(*root)->lchild,c);//c插入左子树
    else if(c>(*root)->data)
        insert(&(*root)->rchild,c);//c插入右子树
}
void Delete(BiTree *p)
{
    BiTree q,s;
    if((*p)->rchild==NULL)//右子树非空则只需重接它的左子树
    {
        q=*p; *p=(*p)->lchild;free(q);
    }
    else if((*p)->lchild==NULL)//只需重接它的右子树
    {
        q=*p; *p=(*p)->rchild;free(q);
    }
    else{//左右子树均不空
        q=*p;
        s=(*p)->lchild;
        while(s->rchild){q=s;s=s->rchild;}//转左,然后向右走到尽头
        (*p)->data=s->data;//s指向被删结点的前驱
        if(q!=*p)q->rchild=s->lchild;//重接*q右子树
        else q->lchild=s->lchild;//重接*q左子树
        free(s);
    }
}
int DeleteBST(BiTree *T,int d)
{
    if(!*T)//待删除关键字不存在
    {
        return 0;
    }
    else
    {
        if(d==(*T)->data)//找到关键字等于d的数据元素
        {
            Delete(T);
            return 1;
        }
        else if(d<(*T)->data)
        {
              return DeleteBST(&(*T)->lchild,d);
        }
        else
        {
              return DeleteBST(&(*T)->rchild,d);
        }
    }
}
void inorder(BiTree root)
{
    if(root!=NULL)
    {
        inorder(root->lchild);
        printf("%d ",root->data);
        inorder(root->rchild);
    }
}
int main()
{
    BiTree root=NULL;
    int a,b,c,d;
    creat(&root);
    scanf("%d%d",&a,&b);
    search(root,a,b);
    printf("\n");
    scanf("%d",&c);
    insert(&root,c);
    inorder(root);
    printf("\n");
    scanf("%d",&d);
    DeleteBST(&root,c);//第二步插入了结点,第三步中需要删除
    DeleteBST(&root,d);
    inorder(root);
    printf("\n");
    return 0;
}




猜你喜欢

转载自blog.csdn.net/rain699/article/details/80457113