此处使用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;
}
}
}