二叉查詢樹的簡單實現(C語言版)
阿新 • • 發佈:2019-02-05
老司機不多說,直接上程式碼
標頭檔案:
#ifndef BINARYTREE_FIND_H_INCLUDED
#define BINARYTREE_FIND_H_INCLUDED
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 // BINARYTREE_FIND_H_INCLUDED
實現:
#include "BinaryTree_Find.h"
#include <stdio.h>
#include <stdlib.h>
struct TreeNode
{
ElementType Element;
SearchTree Left;
SearchTree Right;
};
void FatalError(char * s)
{
printf("%s\n" ,s);
}
void Error(char * s)
{
printf("%s\n",s);
}
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)
{
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("Element 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(T->Element,T->Right);
}
else
{
TmpCell = T;
if(T->Left == NULL)
T = T->Right;
else if(T->Right == NULL)
T = T->Left;
free(TmpCell);
}
return T;
}
int main()
{
SearchTree T = malloc(sizeof(struct TreeNode));
T->Element = 100;
T->Left = NULL;
T->Right = NULL;
int i;
for(i = 0; i < 50; i++)
Insert(i,T);
//Delete(0,T);
Position MIN = FindMin(T);
Position MAX = FindMax(T);
printf("%d\n",MIN->Element);
printf("%d\n",MAX->Element);
free(T);
return 0;
}
程式碼改編自:《資料結構與演算法分析》第二版