数据结构实验7上(二叉搜索树创建与节点删除)

随机生成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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值