/*Tree.h*/
#ifndef _Tree_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);
#endif // !_Tree_H
/*Tree.cpp*/
#include<stdio.h>
#include<stdlib.h>
#include"Tree.h"
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;
else if (T->Left == NULL)
return T;
else
return FindMin(T->Left);
}
Position FindMax(SearchTree T)
{
if (T != NULL)
while (T->Right != NULL)
T = T->Right;
return T;
}
SearchTree Insert(ElementType X, SearchTree T)
{
if (T == NULL)
{
/*Creat and return a one-node tree*/
T = (TreeNode*)malloc(sizeof(struct TreeNode));
if (T = NULL)
printf("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);
/*else X is in the tree already;we'll do nothing*/
return T;
}
SearchTree Delete(ElementType X, SearchTree T)
{
Position TmpCell;
if (T = NULL)
printf("Element not found!");
else if (X > T->Element)/*Go left*/
T->Left = Delete(X, T->Left);
else if (X < T->Element)/*Go right*/
T->Right = Delete(X, T->Right);
/*Found element to be deleted*/
else if (T->Left&&T->Right)/*Two children*/
{
/*Repalce with smallest in right subtree*/
TmpCell = FindMin(T->Right);
T->Element = TmpCell->Element;
T->Right = Delete(T->Element, T->Right);
}
else /*One or zero children*/
{
TmpCell = T;
if (T->Left = NULL)/*Aslo handles 0 child*/
T = T->Right;
else if (T->Right = NULL)
T = T->Left;
free(TmpCell);
}
return T;
}
int main()
{
SearchTree T{} ;
Insert(1, T);
Insert(2, T);
Insert(3, T);
Insert(4, T);
Insert(5, T);
Insert(6, T);
Insert(8, T);
printf("%d", FindMin(T)->Element);
printf("%d", FindMax(T)->Element);
printf("%d", Find(4, T)->Element);
Delete(4, T);
Find(4, T);
MakeEmpty(T);
return 0;
}