随机生成10个正整数,根据生成的顺序在内存中生成一棵二叉搜索树并在控制台输出该树。
从控制台输入一个整数,如果为负数,程序结束;
如果为正数,在二叉搜索树中查找该整数。
如果该数不存在,输出 - 1;如果存在,删除该结点并输出删除结点后的树。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Tree
{
int data;
struct Tree* l;
struct Tree* r;
}tree;
tree* creattree(tree* root, int data)
{
if (root == NULL)
{
tree* newnode = (tree*)malloc(sizeof(tree));
newnode->data = data;
newnode->l = NULL;
newnode->r = NULL;
return newnode;
}
if (data < root->data)
root->l = creattree(root->l, data);
else
root->r = creattree(root->r, data);
return root;
}
void printfnode(int data, char c, int depth)
{
for (int i = 0; i < depth; i++)
printf(" ");
if (data == -1)
printf("%c %c\n", c, '*');
else
printf("%c %d\n", c, data);
}
void printftree(tree* root, char c, int depth)
{
if (root == NULL)
{
printfnode(-1, c, depth);
return;
}
if (root->l == NULL && root->r == NULL)
{
printfnode(root->data, c, depth);
return;
}
printftree(root->r, '/', depth + 1);
printfnode(root->data, c, depth);
printftree(root->l, '\\', depth + 1);
}
tree* findmin(tree* root)
{
if (root == NULL)
return NULL;
else if (root->l == NULL)
return root;
else
return findmin(root->l);
}
tree* del(tree* root, int find, int* flag)
{
if (root == NULL)
{
*flag = -1;
}
else if (find == root->data)
{
if (root->l != NULL && root->r != NULL)
{
int min = findmin(root->r)->data;
root->data = min;
root->r = del(root->r, min, flag);
}
else
{
tree* tnode = root;
if (root->l != NULL)
{
root = root->l;
free(tnode);
}
else if (root->r != NULL)
{
root = root->r;
free(tnode);
}
else
{
free(tnode);
root = NULL;
}
}
*flag = 1;
}
else if (find < root->data)
root->l = del(root->l, find, flag);
else
root->r = del(root->r, find, flag);
return root;
}
int main()
{
tree* root = NULL;
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = rand() % 101;
root = creattree(root, a[i]);
}
printftree(root, ' ', 0);
printf("------------------------------------------------\n");
int find;
int* flag = (int*)malloc(sizeof(int));
*flag = 1;
scanf("%d", &find);
while (find >= 0)
{
root = del(root, find, flag);
if (*flag == -1)
{
printf("no find\n");
printf("------------------------------------------------\n");
}
else
{
printftree(root, ' ', 0);
printf("------------------------------------------------\n");
}
*flag = 1;
scanf("%d", &find);
}
free(flag);
}