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);
}
}