二叉查找树的相关操作
二叉查找树是专门用于二叉树的查找,一般的二叉树查找都是通过遍历来实现,二叉查找树能有效提高查找效率。
- 构造一个空的二叉查找树
- 二叉查找树T存在,销毁树T
- 在二叉查找树中查找值为e.key的结点
- 往二叉查找树中插入值为e.key的结点
- 删除二叉查找树中值为key的结点
代码实现
// Binary_Search_Tree
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef struct {
int key;
} TElemType;
typedef struct BSTNode {
TElemType data;
struct BSTNode *lchild, *rchild;
} BSTNode, *BSTree;
// 构造一个空的二叉查找树
Status InitBST (BSTree &T) {
T = NULL;
}
// 销毁树
Status DestroyBST(BSTree &T) {
if(T->lchild != NULL)
DestroyBST(T->lchild);
if(T->rchild != NULL)
DestroyBST(T->rchild);
T = NULL;
}
// 若二叉查找树 T 中存在值为 key 的结点,则返回该结点指针,否则返回 NULL
BSTree SearchBST(BSTree T, int key) {
if(NULL == T) return NULL; // 查找失败
if(T->data.key == key) return T;
if(T->data.key > key) {
return SearchBST(T->lchild, key);
}
return SearchBST(T->rchild, key);
}
// 若二叉查找树 T 中不存在值为 e.key 的结点,则插入到 T
Status InsertBST(BSTree &T,TElemType e) {
if(NULL == T) {
BSTNode *s;
s = (BSTNode*) malloc (sizeof(BSTNode));
if(NULL == s) return OVERFLOW;
s->data = e;
s->lchild = NULL;
s->rchild = NULL;
T = s;
return TRUE;
}
if(e.key < T->data.key) return InsertBST(T->lchild,e);
if(e.key > T->data.key) return InsertBST(T->rchild,e);
return FALSE;
}
// 删除结点操作
void DeleteNode(BSTree &p) {
BSTNode *q,*s;
q = p;
if(NULL == p->rchild) {
p = p->lchild;
free(q);
} else if(NULL == p->lchild) {
p = p->rchild;
free(q);
} else {
s = p->lchild;
while (s->rchild != NULL) {
q = s;
s = s->rchild;
}
p->data = s->data;
if(q == p)
q->lchild = s->lchild;
else q->rchild = s->lchild;
free(s);
}
}
// 若二叉查找树 T 中存在值为 key 的结点,则删除
Status DeleteBST(BSTree &T,int key) {
if(NULL == T) return FALSE;
if(key == T->data.key) {
DeleteNode(T);
return TRUE;
}
else if(key < T->data.key)
return DeleteBST(T->lchild,key);
return DeleteBST(T->rchild,key);
}
// 输出树
void puttree(BSTree &t){
if(NULL == t) return ;
else{
puttree(t->lchild);
printf("%d ",t->data);
puttree(t->rchild);
}
}
int main() {
TElemType E;
int i;
int key_1, key_2, key_3;
int a[10];
BSTree t, temp_1, temp_2;
Status temp_3;
printf("enter array a[10](integer):\n");
for(i = 0;i < 10;i++) { //构造数组a[10]
scanf("%d",&a[i]);
}
InitBST(t); // 构造一个空的二叉查找树
for(i = 0;i<10;i++) {
E.key = a[i];
InsertBST(t,E); // 插入值为 E.key的结点
}
printf("Tree is made up from array a[10]:\n");
puttree(t); // 输出树
printf("\n");
printf("enter key_1(for searching), key_2(for searching), key_3(for deleting):\n");
scanf("%d %d %d",&key_1, &key_2, &key_3);
temp_1 = SearchBST(t,key_1);
if(temp_1) { // 查找是否有存在结点值为key_1
printf("%d\n", temp_1->data.key);
} else {
printf("%d can't be found\n",key_1);
}
temp_2 = SearchBST(t,key_2);
if(temp_2) { // 查找是否有存在结点值为key_2
printf("%d\n", temp_2->data.key);
} else {
printf("%d can't be found\n",key_2);
}
temp_3 = DeleteBST(t,key_3);
if(temp_3 == TRUE) { //删除值为key_3的结点
printf("%d has been delete\n", key_3);
} else {
printf("%d can't be found\n",key_3);
}
}