level 7
#include<stdio.h>
#include<stdlib.h>
struct Tree* makeempty(struct Tree* t);//1
struct Tree* find(int x, struct Tree* t);//2
struct Tree* findmin(struct Tree* t);//3
struct Tree* findmax(struct Tree* t);//4
struct Tree* insert(int x, struct Tree* t);//5
struct Tree* Delete(int x, struct Tree* t);//6
void printtree(struct Tree* t);//中序打印 7
struct Tree
{
int element;
struct Tree* left;
struct Tree* right;
};
int main(void)
{
struct Tree* min;
struct Tree* max;
struct Tree* node;
struct Tree* root;
root = insert(6, NULL);
for (int i = 0; i < 6; i++)
{
insert(i, root);
}
printtree(root);
node = find(4, 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);
printtree(root);
return 0;
}
2024年02月17日 08点02分
3
level 7
struct Tree* makeempty(struct Tree* t)//1
{
if (t != NULL)
{
makeempty(t->left);
makeempty(t->right);
free(t);
}
return NULL;
}
struct Tree* find(int x, struct Tree* t)//2
{
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)//3
{
if (t == NULL)
{
return NULL;
}
else if (t->left == NULL)
{
return t;
}
else
{
return findmin(t->left);
}
}
struct Tree* findmax(struct Tree* t)//4
{
if (t != NULL)
{
while (t->right != NULL)
{
t = t->right;
}
}
return t;
}
struct Tree* insert(int x, struct Tree* t)//5
{
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)//6删除
{
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->left);
}
else if (t->left != NULL && t->right != NULL)
{
tmp = findmin(t->right);
t->element = tmp->element;
t->right = Delete(t->element, t->right);
}
else
{
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)//7
{
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);
}
}
2024年02月17日 08点02分
4