二叉查找树ADT--C语言描述

首先给出此ADT的声明:

 struct TreeNode;
typedef struct TreeNode *Position;
typedef struct TreeNode *SearchTree; SearchTree MakeEmpty(SearchTree T);
Position Find(ElementType X, SearchTree T);
Position FindMax(SearchTree T);
Position FindMin(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;
};

1、MakeEmpty的实现

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

2、Find的实现

 Position Find(ElementType X, SearchTree T){
if(T == NULL)
return NULL;
else if(X < T->Element)
return Find(X, T->Left);
else if(X > T->Element)
return Find(X, T->Right);
else
return T;
}

3、FindMax和FindMin的实现(一个递归 一个非递归)

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

4、Insert的实现

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

5、Delete的实现

 SearchTree Delete(ElementType X, SearchTree T){
Position TmpCell; if(T == NULL)
printf("Element Not Found\n");
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(TmpCell->Element, T->Right);
}
else{
TmpCell = T;
if(!(T->Left))
T = T->Right;
else if(!(T->Right))
T = T->Left;
free(TmpCell);
}
return T;
}
上一篇:数据结构:二叉查找树(C语言实现)


下一篇:求两个字符串最长子串的LCS算法 C语言实现(简短的实现函数)