#include <stdlib.h>
#include <stdio.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0k
typedef int Status;
typedef int KeyType;
typedef struct
{
KeyType key;
}RcdType;
typedef struct BSTNode
{
RcdType data;
struct BSTNode *lchild, *rchild;
}BSTNode, *BSTree;
Status InitBSTree(BSTree &t)
{
t = NULL;
return OK;
}
Status DestoryBSTree(BSTree &t)
{
if (t == NULL) return OK;
BSTree l, r;
l = t->lchild;
r = t->rchild;
free(t);
t = NULL;
DestoryBSTree(l);
DestoryBSTree(r);
return OK;
}
/*递归查找*/
BSTree SearchBSTree_recursive(BSTree t, KeyType key)
{
if (t == NULL) return NULL;
if (t->data.key == key) return t;
if (key < t->data.key) return SearchBSTree_recursive(t->lchild, key);
return SearchBSTree_recursive(t->rchild, key);
}
/*非递归查找*/
BSTree SearchBSTree_unrecursive(BSTree t, KeyType key)
{
while (t != NULL) {
if (t->data.key == key) return t;
if (key < t->data.key) t = t->lchild;
else t = t->rchild;
}
return NULL;
}
/*递归插入*/
Status InsertBST_recursive(BSTree &t, RcdType e)
{
if (t == NULL) {
if (NULL == (t = (BSTNode*)malloc(sizeof(BSTNode)))) return ERROR;
t->data = e;
t->lchild = t->rchild = NULL;
return TRUE;
}
if (e.key < t->data.key) return InsertBST_recursive(t->lchild, e);
if (e.key > t->data.key) return InsertBST_recursive(t->rchild, e);
return ERROR;
}
/*非递归插入*/
Status InsertBST_unrecursive(BSTree &t, RcdType e)
{
BSTNode *s;
BSTree p = t;
if (NULL == (s = (BSTNode*)malloc(sizeof(BSTNode)))) return ERROR;
s->data = e;
s->lchild = s->rchild = NULL;
if (t == NULL) {
t = s;
return OK;
}
while (p != NULL) {
if (e.key == p->data.key) return ERROR;
if (e.key < p->data.key) {
if (p->lchild == NULL) {
p->lchild = s;
return OK;
}
p = p->lchild;
}
else {
if (p->rchild == NULL) {
p->rchild = s;
return OK;
}
p = p->rchild;
}
}
return OK;
}
void DeleteNode(BSTree &p)
{
BSTNode *q, *s;
if (p->lchild == NULL) { //没有左子树
q = p;
p = p->rchild;
free(q);
}
else { //有左子树
q = p;
s = p->lchild;
while (s->rchild != NULL) {
q = s;
s = s->rchild;
}
p->data = s->data;
free(s);
if (p != q) q->rchild = NULL;
else p->lchild = NULL; //没有进入while循环
}
}
Status DeleteBST(BSTree &t, KeyType key)
{
if (t == NULL) return ERROR;
if (key == t->data.key) {
DeleteNode(t);
return OK;
}
if (key < t->data.key) return DeleteBST(t->lchild, key);
return (t->rchild, key);
}
BSTree createBSTree(RcdType rcd[],int n)
{
if (n <= 0) return NULL;
BSTree bst = NULL;
for (int i = 0; i < n; i++) {
InsertBST_recursive(bst, rcd[i]);
}
return bst;
}
int main()
{
/*test code*/
RcdType rcd[5];
KeyType key[5] = { 3, 2, 5, 1, 4 };
int i = 0;
for (i = 0; i < 5; i++) {
rcd[i].key = key[i];
}
BSTree tree = createBSTree(rcd, 5);
system("pause");
return 0;
}
二叉排序树
最新推荐文章于 2020-08-03 12:46:56 发布