二叉排序树

#include<stdio.h>
#include<stdlib.h>
typedef int type;
typedef struct node
{
    type key;
    struct node *lchild,*rchild;
}bsnode;
typedef bsnode *bstree;
//非递归查找x的位置,通过二级指针返回其父亲节点位置和其位置
void bssearch(bstree t,type x,bstree *f,bstree*p)
{
    *f=NULL;
    *p=t;
    while(*p)
    {
        if(x==(*p)->key)
        return ;
        *f=*p;
        *p=(x<(*p)->key)?(*p)->lchild:(*p)->rchild;
    }
    return ;
}
//递归查找x的位置
bstree Bssearch(bstree t ,type x)
{
    if(t==NULL||x==t->key)
        return t;
    if(x<t->key)
        return Bssearch(t->lchild,x);
    else return Bssearch(t->rchild,x);
}
//树中插入一个值为x的节点
void insert(bstree *t,type x)
{
    bstree f=NULL,p;//f为插入位置的双亲节点
    p=*t;
    while(p)
    {
        if(p->key==x)//已存在该值,结束
            return ;
        f=p;
        if(x<p->key)
            p=p->lchild;
        else p=p->rchild;
    }
    p=(bstree)malloc(sizeof(bsnode));
    p->key=x;
    p->lchild=p->rchild=NULL;
    if(*t==NULL)//树为空树,新插入的节点为根节点
        *t=p;
    else//插入到父节点相应位置
    {
        if(x<f->key)
            f->lchild=p;
        else f->rchild=p;
    }
}


//创建一颗树
bstree creatbstree()
{
    bstree t=NULL;
    type x;
    while(scanf("%d",&x)!=EOF,x>0)
        insert(&t,x);
    return t;
}
bstree DelBstree(bstree t,type x)
{
    bstree p,q,child;
    //查找到该点的位置,和双亲位置
    bssearch(t,x,&p,&q);
    if(q)//如果查找到
    {
        if(q->lchild==NULL&&q->rchild==NULL)//叶子节点
        {
            if(p)
            {
                if(p->lchild==q)//是双亲的左儿子树
                    p->lchild=NULL;
                else p->rchild=NULL;//双亲的右儿子树
            }
            else t=NULL;//删除的是根节点
            free(q);
        }
        else if(q->rchild==NULL)//只有左儿子树
        {
            if(p)//存在双亲,将他的左儿子树代替他的位置
            {
                if(p->lchild==q)//他是他双亲的左儿子树
                    p->lchild=q->lchild;//右儿子树
                else p->rchild=q->lchild;
            }
            else t=q->lchild;//被删除的是根节点
            free(q);
        }
        else if(q->lchild==NULL)//只有右儿子树(类似)
        {
            if(p)
            {
                if(p->lchild==q)
                    p->lchild==q->rchild;
                else p->rchild=q->rchild;
            }
            else t=q->rchild;
            free(q);
        }
        else//既有左子树,又有右子树
        {   //将他的右儿子代替他的位置,他的左儿子放在有儿子树中序下首位
            child=p->rchild;
            while(child->lchild)
                child=child->lchild;
            child->lchild=q->lchild;//找到右子树中序下首点
            if(p)
            {
                if(p->lchild==q)//他是他双亲的左儿子
                    p->lchild=q->rchild;
                else p->rchild=q->rchild;
            }
            else t=q->rchild;//删除的是根节点
            free(q);
        }
    }
    return t;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Thereisnospon/p/4768504.html