BinarySearchTree
#include<stdlib.h>
#include<malloc.h>
#include<stdio.h>
struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree;
typedef char 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;
};
/* Routine to make an empty tree */
SearchTree MakeEmpty(SearchTree T) {
if (T != NULL) {
MakeEmpty(T->Left);
MakeEmpty(T->Right);
free(T);
}
return NULL;
}
/* Find operation for binary search trees */
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;
}
/* Recursive implementation of FindMin for biany search trees */
Position FindMin(SearchTree T) {
if (T == NULL)
return NULL;
else if (T->Left == NULL)
return T;
else
return FindMin(T->Left);
}
/* Nonrecursive implementation of FindMax for binary search trees */
Position FindMax(SearchTree T) {
if (T != NULL)
while (T->Right != NULL)
T = T->Right;
return T;
}
/* Insertion into a binary search tree */
SearchTree Insert(ElementType X, SearchTree T) {
if (T == NULL) {
/* Create and return a one-node tree */
T = (SearchTree) malloc(sizeof(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;
}
/* Deletion routinue for binary search tree */
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);
else if (T->Left && T->Right) {
/* Replace 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)
T = T->Right; /* Also handles 0 children */
else if (T->Right == NULL)
T = T->Left;
free(TmpCell);
}
return T;
}