二叉排序树

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
typedef struct node{
    int data;
    struct node *lc,*rc;
}Binode,*Bitree;

void Insert(Bitree &T,int &e)
{
    Bitree s;
    if (!T)
    {
        s=(Bitree)malloc(sizeof(Binode));
        s->data=e;
        s->lc=NULL;
        s->rc=NULL;
        T=s;
    }
     else if (e<T->data)
            Insert(T->lc,e);
        else
            Insert(T->rc,e);
}

void CreatBitree (Bitree &T)
{
    int e;
    T=NULL;
    scanf("%d",&e);
    while (e!=0)
    {
        Insert(T,e);
        scanf ("%d",&e);
    }
}
void Search(Bitree &T,int &key)
{
    if (!T)
    {
        printf ("查找失败\n");
    }
    else
        if (key==T->data)
        printf("找到关键字%d\n",T->data);
    else if (key<T->data)
        Search(T->lc,key);
    else
        Search(T->rc,key);
}

void Delete(Bitree &T)
{
    Bitree q,s;
    if(!T->rc)
    {
        q=T;
        T=T->lc;
        free(q);
    }
    else
        if (!T->lc)
    {
        q=T;
        T=T->rc;
        free(q);
    }
    else
    {
        s=T;
        s=T->rc;
        while (s->rc)
        {
            q=s;
            s=s->rc;
        }
        T->data=s->data;
        if(q!=T)
            q->rc=s->lc;
        else
            q->lc=s->lc;
        delete s;
    }
}
void DeleteBitree(Bitree &T,int &key)
{
    if (!T)
        printf("没有找到你要删除的关键字\n");
    else
    {
        if (key==T->data)
            Delete(T);
        else if(key<T->data)
           DeleteBitree(T->lc,key);
        else
           DeleteBitree(T->rc,key);
    }
}
void Inorder(Bitree &T)
{
    if (T)
    {
        Inorder(T->lc);
        printf ("%d ",T->data);
        Inorder(T->rc);
    }
}
int main ()
{
    int key;
    int n;
    Bitree b;
    printf ("输入一组关键字(当输入为0时结束)\n");
    CreatBitree(b);

    Inorder(b);
     printf ("\n\n");
    while (1)
    {
        printf("选择操作\n1.插入\n2.删除\n3.查找\n");
        scanf ("%d",&n);
        switch (n)
        {
            case 1:
                {
                    printf("输入要插入的关键字\n");
                    scanf ("%d",&key);
                    Insert (b,key);
                    Inorder(b);
                    printf ("\n\n");
                    break;
                }
            case 2:
                {
                    printf("输入要删除的关键字\n");
                    scanf ("%d",&key);
                    DeleteBitree(b,key);
                    Inorder(b);
                    printf ("\n\n");
                    break;
                }
            case 3:
                {
                    printf("输入要查找的关键字\n");\
                    scanf ("%d",&key);
                    Search(b,key);
                    printf("\n");
                    break;
                }
        }
    }
    return 0;
}

你可能感兴趣的:(二叉排序树)