BST树--C语言实现

bsttree.h

#ifndef _BSTTREE_H_
#define _BSTTREE_H_

struct BstNode;
typedef int ElementType;
typedef struct BstNode *Position;
typedef struct BstNode *BstTree;
BstTree MakeEmpty(BstTree T);
Position Find(ElementType X, BstTree T);
Position FindMax(BstTree T);
Position FindMin(BstTree T);
BstTree Insert(ElementType X, BstTree T);
BstTree Delete(ElementType X, BstTree T);
ElementType Retrieve(Position P);
void InOrder(BstTree T,void (*pfun)(ElementType Element));

#endif

bsttree.c

#include<stdio.h>
#include<stdlib.h>
#include"bsttree.h"

struct BstNode
{
    ElementType Element;
    BstTree Left;
    BstTree Right;
};

BstTree MakeEmpty(BstTree T)
{
    if (T != NULL)
    {
        MakeEmpty(T->Left);
        MakeEmpty(T->Right);
        free(T);
    }
    return NULL;
}
Position Find(ElementType X, BstTree T)
{
    if (T == NULL)
        return NULL;
    if (X < T->Element)
        return Find(X, T->Left);
    else if (X>T->Element)
        return Find(X, T->Right);
    else
        return T;
}
Position FindMax(BstTree T)
{
    if (T != NULL)
        while (T->Right != NULL)
            T = T->Right;
    return T;
}
Position FindMin(BstTree T)
{
    if (T == NULL)
        return NULL;
    if (T->Left == NULL)
        return T;
    else
        return FindMin(T->Left);
}
BstTree Insert(ElementType X, BstTree T)
{
    if (T == NULL)
    {
        T = (BstTree)malloc(sizeof(BstNode));
        if (T == NULL)
        {
            printf("FAILURE!\n");
            exit(EXIT_FAILURE);
        }
        else
        {
            T->Element = X;
            T->Left = T->Right = NULL;
        }
    }
    else if (X < T->Element)
        T->Left = Insert(X, T->Left);
    else if (X > T->Element)
        T->Right = Insert(X, T->Right);
    return T;
}
BstTree Delete(ElementType X, BstTree T)
{
    if (T == NULL)
    {
        printf("Element Not Found!\n");
        return NULL;
    }
    if (X < T->Element)
        T->Left = Delete(X, T->Left);
    else if (X>T->Element)
        T->Right = Delete(X, T->Right);
    else
    {
        if (T->Left && T->Right)
        {
            T->Element = FindMax(T->Left)->Element;
            T->Left = Delete(T->Element, T->Left);
        }
        else
        {
            Position temp = T;
            T = T->Left ? T->Left : T->Right;
            free(temp);
        }
    }
    return T;
}
ElementType Retrieve(Position P)
{
    if (P != NULL)
        return P->Element;
}
void InOrder(BstTree T, void(*pfun)(ElementType Element))
{
    if (T)
    {
        InOrder(T->Left,pfun);
        (*pfun)(T->Element);
        InOrder(T->Right,pfun);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值