#include<stdio.h>
#include<stdlib.h>
//链表类型声明
struct Tree
{
int element;
struct Tree *left;
struct Tree* right;
};
//建立一棵空树(清空树)
struct Tree* makeEmpty(struct Tree* t)
{
if (t != NULL)
{
makeEmpty(t->left);
makeEmpty(t->right);
free(t);
}
return NULL;
}
//查找树中某个结点
struct Tree* find(int x, struct Tree* 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;
}
}
//查找树中的最小值(循环实现)
struct Tree* findMin(struct Tree* t)
{
if (t != NULL)
{
while (t->left != NULL)
{
t = t->left;
}
return t;
}
//递归实现
/*
if (t == NULL)
{
return NULL;
}
else if (t->left == NULL)
{
return t;
}
else
{
return findMin(t->left);
}
*/
}
//查找树中的最大值(递归实现)
struct Tree* findMax(struct Tree* t)
{
if (t == NULL)
{
return NULL;
}
else if (t->right == NULL)
{
return t;
}
else
{
return findMax(t->right);
}
//循环实现
/*
if (t != NULL)
{
while (t->right != NULL)
{
t = t->right;
}
}
return t;
*/
}
//插入某个元素
struct Tree* insert(int x, struct Tree* t)
{
if (t == NULL)
{
t = (struct Tree*)malloc(sizeof(struct Tree));
if (t == NULL)
{
printf("Out of space!\n");
return NULL;
}
else
{
t->element = x;
t->left = NULL;
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;
}
//删除某个元素
struct Tree* Delete(int x, struct Tree* t)
{
struct Tree* tmp;
if (t == NULL)
{
printf("Element not found!\n");
return NULL;
}
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 != NULL && t->right != NULL) //两个儿子
{
tmp = findMin(t->right);
t->element = tmp->element;
t->right = Delete(t->element, t->right);
}
else //0个或一个儿子
{
tmp = t;
if (t->left == NULL)
{
t = t->right;
}
else if (t->right == NULL)
{
t = t->left;
}
free(tmp);
}
return t;
}
//使用中序遍历打印
void printTree(struct Tree* t)
{
if (t == NULL)
{
printf("Empty tree!\n");
return;
}
//打印左子树
if (t->left != NULL)
{
printTree(t->left);
}
//打印根结点
printf("element is %d\n", t->element);
//打印右子树
if (t->right != NULL)
{
printTree(t->right);
}
}
//主函数
int main(void)
{
struct Tree* min;
struct Tree* max;
struct Tree* node;
struct Tree* root;
//插入某个元素
root = insert(6, NULL);
insert(4, root);
insert(3, root);
insert(7, root);
insert(1, root);
insert(8, root);
insert(12, root);
//使用中序遍历打印
printTree(root);
//查找树中某个结点
node = find(8, root);
printf("find node is:%d\n", node->element);
//查找树中的最小值
min = findMin(root);
printf("min is:%d\n", min->element);
//查找树中的最大值
max = findMax(root);
printf("max is:%d\n", max->element);
//删除某个元素
Delete(4, root);
Delete(3, root);
Delete(8, root);
//使用中序遍历打印
printTree(root);
//建立一棵空树(清空树)
makeEmpty(root);
return 0;
}
06-11
01-20
05-17
235
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交