#include<stdio.h>
#include<malloc.h>
typedef int Element;
typedef struct trees *Pointer;
typedef struct trees {
Element data;
Pointer Left;
Pointer Right;
}Tree;
typedef Tree *BinTree;
BinTree createTree()
{
Tree *T = NULL;
return T;
}
BinTree TreeInsert(BinTree T, int x)
{
if (T == NULL)
{
T = (BinTree)malloc(sizeof(Tree));
if (T == NULL)
return NULL;
T->data = x;
T->Left = T->Right = NULL;
}
else
{
if (T->data > x)
T->Left = TreeInsert(T->Left, x);
else if (x > T->data)
T->Right = TreeInsert(T->Right, x);
}
return T;
}
BinTree FindMin(BinTree BT)
{
if (!BT)//空树
return BT;
else if (!BT->Left)
return BT;//在结点的左子树寻找最小值
else
FindMin(BT->Left);
}
BinTree FindMax(BinTree T)
{
Pointer B = T;
if (T)
{
while (B->Right)
B = B->Right;
}
return B;
}
BinTree Delete(Pointer T, Element X)
{
if (!T)
printf("the tree is null!\n");
else
{
if (X < T->data)
T->Left = Delete(T->Left, X);
else if (X > T->data)
T->Right = Delete(T->Right, X);
else//删除选择
{
//待删除结点有左右两个子树
if (T->Left && T->Right)
{//右子树中寻找最小值,替代结点
Pointer tmp = FindMin(T->Right);
T->data = tmp->data;//替代
//从右子树中删除tmp结点
T->Right = Delete(T->Right, tmp->data);
}
else//待删除结点只有一个子节点或者没有子结点
{
BinTree tmp = T;
if (!T->Left)//没有左结点
T = T->Right;
else
T = T->Left;
free(tmp);
tmp = NULL;
}
}
}
return T;
}
void print(BinTree BT)
{
BinTree queue[100] = { NULL };
if (BT == NULL)
printf("空树!\n");
else
{
int tail = 0, front = 0;
queue[tail++] = BT;
Pointer T = NULL;
while (tail != front) {
T = queue[front++];
printf("%d\n", T->data);
if (T->Left)
queue[tail++] = T->Left;
if (T->Right)
queue[tail++] = T->Right;
}
}
}
int main(void)
{
Pointer T = NULL;
T = createTree();
int data = 0;
printf("输入树节点的值!\n输入 0 时输入结束!\n");
scanf("%d", &data);
while (data) {
T = TreeInsert(T, data);
scanf("%d", &data);
}
printf("最大值为:%d\n", FindMax(T)->data);
print(T);
printf("请输入一个要删除的结点的值!\n");
scanf("%d", &data);
Delete(T, data);
print(T);
return 0;
}
二叉搜索树简单操作集
最新推荐文章于 2021-10-14 20:01:50 发布