二叉查找树(二叉排序树)(C语言)

#include<stdio.h>
#include "fatal.h"
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
typedef int ElementType;
SearchTree MakeEmpty(SearchTree T);
Position Find(ElementType X,SearchTree T);
Position FindMin(SearchTree T);
Position FindMax(SearchTree T);
SearchTree Insert(ElementType X,SearchTree T);
SearchTree Delete(ElementType X,SearchTree T);
ElementType Retrieve(Position P);
struct TreeNode 
{
    ElementType Element;
    SearchTree left;
    SearchTree right;
};

SearchTree MakeEmpty(SearchTree T)
{
    if(T!=NULL)
    {
        MakeEmpty(T->left);
        MakeEmpty(T->right);
        free(T);
    }
    return NULL;
}

Position Find(ElementType X,SearchTree 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 FindMin(SearchTree T)
{
    if(T==NULL)
        return NULL;
    if(T->left==NULL)
        return T;
    else
        return FindMin(T->left);
}

Position FindMax(SearchTree T)
{
    if(T==NULL)
        return NULL;
    else if(T->right==NULL)
        return T;
    else
        return FindMax(T->right);
}

SearchTree Insert(ElementType X,SearchTree T)
{
    if(T==NULL)
    {
        T=malloc(sizeof(struct TreeNode));
        if(T==NULL)
            FatalError("Out of space!!!");
        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;
}

SearchTree Delete(ElementType X,SearchTree T)
{
    Position TmpCell;
    if(T==NULL)
        Error("Error not found");
    else 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)
    {
        TmpCell=FindMin(T->right);
        T->Element=TmpCell->Element;
        T->right=Delete(X,T->right);
    }
    else
    {
        TmpCell=T;
        if(T->left==NULL)
            T=T->right;
        else if(T->right=NULL)
            T=T->left;
        free(TmpCell);
    }
    return T;
}
ElementType Retrieve(Position P)
{
    if(P==NULL)
        return -1;
    else
        return P->Element;
}

 

二叉查找树(二叉排序树)(C语言),布布扣,bubuko.com

二叉查找树(二叉排序树)(C语言)

上一篇:【Java编码准则】の #11不要使用Object.equals()来比較密钥值


下一篇:用Eclipse给安卓应用进行签名