栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构实验6(二叉树)下

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构实验6(二叉树)下

随机生成10个[0, 100].上的随机数,使用二叉树对
其进行从小到大的排序,并输出排序后的结果。

#include
#include

typedef struct Tree
{
	int data;
	struct Tree* lt;
	struct Tree* rt;
}tree;

tree* creattree(tree* root, int data)
{	
	if (root == NULL)
	{	
		tree* newnode = (tree*)malloc(sizeof(tree));
		newnode->data = data;
		newnode->lt = NULL;
		newnode->rt = NULL;
		return newnode;
	}
	 if (data < root->data)
		root->lt = creattree(root->lt, data);
	else
		root->rt = creattree(root->rt, data);
	 return root;
}

void printfinord(tree* root)
{
	if (root->lt)
	{
		printfinord(root->lt);
	}
	printf("%d ", root->data);
	if (root->rt)
	{
		printfinord(root->rt);
	}
}

int main()
{
	tree* root = NULL;
	int a[10];
	for (int i = 0; i < 10; i++)
	{
		a[i] = rand() % 101;
		root = creattree(root, a[i]);
		printf("%d ", a[i]);
	}
	printf("n");
	printfinord(root);
}

从控制台输入任意一组数字,以此在内存中重构一棵完全二叉树。

要求:每输入一个数字,立刻生成对应的二叉树并在控制台输出此二叉树。

#include
#include
#include

typedef struct Tree
{
	char data[10];
	struct Tree* lt;
	struct Tree* rt;
}tree;

typedef struct Que
{
	struct Tree* t[100];
	int pre;
	int lat;
}que;

void creattree(tree** root, que** list, char* data)
{
	tree* newnode = (tree*)malloc(sizeof(tree));
	strcpy(newnode->data, data);
	newnode->lt = NULL;
	newnode->rt = NULL;
	if ((*list)->pre == (*list)->lat)
	{
		(*list)->pre = ((*list)->pre + 1) % 100;
		(*list)->t[(*list)->pre] = newnode;
		*root = newnode;
	}
	else if ((*list)->t[((*list)->lat + 1) % 100]->lt == NULL)
	{
		(*list)->t[((*list)->lat + 1) % 100]->lt = newnode;
		(*list)->pre = ((*list)->pre + 1) % 100;
		(*list)->t[(*list)->pre] = newnode;
	}
	else
	{
		(*list)->t[((*list)->lat + 1) % 100]->rt = newnode;
		(*list)->lat = ((*list)->lat + 1) % 100;
		(*list)->pre = ((*list)->pre + 1) % 100;
		(*list)->t[(*list)->pre] = newnode;
	}
}

void printfnode(char* data, char c, int depth)
{
	for (int i = 0; i < depth; i++)
		printf("	");
	printf("%c %sn", c, data);
}

void printftree(tree* root, char c, int depth)
{
	if (root == NULL)
	{
		printfnode("*", c, depth);
		return;
	}
	if (root->lt == NULL && root->rt == NULL)
	{
		printfnode(root->data, c, depth);
		return;
	}
	printftree(root->rt, '/', depth + 1);
	printfnode(root->data, c, depth);
	printftree(root->lt, '\', depth + 1);
}

int main()
{
	tree* root = (tree*)malloc(sizeof(tree));
	que* list = (que*)malloc(sizeof(que*));
	char str[10];
	list->pre = 0;
	list->lat = 0;
	gets(str);
	while (*str != '*')
	{
		creattree(&root, &list, str);
		printftree(root, ' ', 0);
		printf("--------------------------------------------------------------n");
		gets(str);
	}
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/960129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号