数据结构实验树的代码演示:

此处使用C++环境运行C,目的是为了使用&引用符

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#define overflow -1
#define OK 1
#define ERROR 0
typedef char TElemType;
typedef int Status;
typedef struct BiTNode
{
	TElemType data;
	struct BiTNode* lchild, * rchild;
} BiTNode;
typedef BiTNode* BiTree;
Status CreateBiTree(BiTree& T) {
	char ch;
	printf("字符输入‘#’,则树该部分结束,请输入该节点的元素:\n");
	scanf("%c", &ch);
	getchar();//while(getchar()!='\n');
	if (ch == '#') {
		T = NULL;
	}
	else {
		if (!(T = (BiTNode*)malloc(sizeof(BiTNode))))
			exit(overflow);
		T->data = ch;
		printf("输入%c左孩子\n",T->data);
		CreateBiTree(T->lchild);
		printf("输入%c右孩子\n", T->data);
		CreateBiTree(T->rchild);
		return OK;
	}
	return overflow;
}
Status LRD(BiTree T)
{
	if (T == NULL) {
		return ERROR;
	}
	else {
		LRD(T->lchild);
		LRD(T->rchild);
		printf("%c ", T->data);
	}
	return OK;
}//遍历后序
Status LDR(BiTree T)
{
	if (T == NULL) {
		return ERROR;
	}
	else {
		LDR(T->lchild);
		printf("%c ", T->data);
		LDR(T->rchild);
	}
	return OK;
}//遍历中序
Status DLR(BiTree T)
{
	if (T == NULL) {
		return ERROR;
	}
	else {
		printf("%c ", T->data);
		DLR(T->lchild);
		DLR(T->rchild);
	}
	return OK;
}//遍历先序

//销毁树
Status xiaohui(BiTree& T) {
	if (T == NULL) {
		return 0;
	}
	else {
		xiaohui(T->lchild);
		xiaohui(T->rchild);
		free(T);
	}
	T = NULL;
	return OK;
}
Status shendu(BiTree T) {
	//树深度
	int a, b;
	int max;
	if (T == NULL) {
		return 0;
	}
	else {
		a = shendu(T->lchild);
		b = shendu(T->rchild);
		if (a >= b) {
			max = a;
		}
		else {
			max = b;
		}
		return max + 1;
	}
}
void OperateMenu()
{
	printf("0.退出,1.初始化树,2.后序遍历,3.中序遍历,4.先序遍历,5.销毁树,6.树深度\n");
}//菜单
int main()
{
	BiTree T;
	T = NULL;
	int a;
	while (1) {
		OperateMenu();
		scanf("%d", &a);
		getchar();
		switch (a)
		{
		case 0:return 0;
		case 1:
			a = CreateBiTree(T);
			if (a == OK) {
				printf("初始树建立成功\n");
			}
			break;
		case 2:
			
			
				printf("后序遍历\n");
				a=LRD(T);
				if (a == ERROR) {
					printf("空树\n");
				}
				printf("\n");
				break;
			
		case 3:
			
				printf("中序遍历\n");
				a=LDR(T);
				if (a == ERROR) {
					printf("空树\n");
				}
				printf("\n");
				break;
			
		case 4:
			
			
				printf("先序遍历\n");
				a=DLR(T);
				if (a == ERROR) {
					printf("空树\n");
				}
				printf("\n");
				break;
			
		case 5:
			if (T == NULL) {
				printf("请先初始化树,选择功能1\n");
				break;
			}
			else {
				a = xiaohui(T);
				if (a == OK) {
					printf("销毁成功\n");
				}
				break;
			}
		case 6:
			
			
				a = shendu(T);
				printf("深度为:%d\n", a);
				break;
			
		default:
			printf("输入有误,请重新输入\n");
			break;
		}
	}
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值