数据结构(C语言):链式二叉树的基本操作及其实现

#define _CRT_SECURE_NO_WARNINGS 1
//链式二叉树
#include 
#include
#include
#include 
using namespace std;
#define MAX_SIZE 100
typedef char TElemType;
typedef struct BiNode {
	TElemType data;//结点数据
	struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
void preOrderTraverse(BiTree T) {
	if (!T) {
		return;
	}
	printf("%c\n", T->data);
	preOrderTraverse(T->lchild);
	preOrderTraverse(T->rchild);
}//先序遍历
void middleOrderTraverse(BiTree T) {
	if (T == NULL) {
		return;
	}
	middleOrderTraverse(T->lchild);
	printf("%c\n", T->data);
	middleOrderTraverse(T->rchild);
}//中序遍历
void lastOrderTraverse(BiTree T) {
	if (T == NULL) {
		return;
	}
	lastOrderTraverse(T->lchild);
	lastOrderTraverse(T->rchild);
	printf("%c\n", T->data);
}//后序遍历
void CreatBiTree(BiTree& T) {
	TElemType ch;
	cin >> ch;
	if (ch == '#') {
		T = NULL;
	}
	else {
		T = (BiTree)malloc(sizeof(BiNode));
		if (!T) {
			exit(OVERFLOW);
		}
		T->data = ch;
		CreatBiTree(T->lchild);//构造左子树
		CreatBiTree(T->rchild);//构造右子树
	}
}
void DestoryBiTree(BiTree T) {
	if (T == NULL)
		return;

	DestoryBiTree(T->lchild);//销毁左子树
	DestoryBiTree(T->rchild);//销毁右子树
	printf("%c\n", T->data);
	free(T);//释放根结点
}//销毁二叉树
int DepthBiTree(BiTree T) {
	int h1, h2;
	if (T == NULL) {
		return 0;
	}
	else {
		h1 = DepthBiTree(T->lchild);
		h2 = DepthBiTree(T->rchild);
		if (h1 > h2) {
			return h1 + 1;
		}
		else {
			return h2 + 1;
		}
	}
}//深度
int countTree(BiTree T) {
	int lCount, rCount;
	if (T == NULL) {
		return 0;
	}
	lCount = countTree(T->lchild);
	rCount = countTree(T->rchild);
	return lCount + rCount + 1;
}
void opreatMenu() {
	printf("\n");
	printf("请选择你的操作:\n");
	printf("1.创建二叉树\n");
	printf("2.先序遍历\n");
	printf("3.中序遍历\n");
	printf("4.后序遍历\n");
	printf("5.二叉树深度\n");
	printf("6.二叉树总结点\n");
	printf("0.退出\n");
	printf("\n");
}
int main() {
	BiTree T = nullptr;
	int n;
	do {
		opreatMenu();
		scanf("%d", &n);
		printf("\n");
		switch (n) {
		case 1:
			CreatBiTree(T);
			break;
		case 2:
			preOrderTraverse(T);
			break;
		case 3:
			middleOrderTraverse(T);
			break;
		case 4:
			lastOrderTraverse(T);
			break;
		case 5:
			printf("深度为%d", DepthBiTree(T));
			break;
		case 6:
			printf("总结点为%d", countTree(T));
			break;
		case 0:
			DestoryBiTree(T);
			printf("再见!");
			break;
		default:
			printf("请重新输入");
			break;
		}
	} while (n);
	return 0;
}

你可能感兴趣的:(数据结构,c语言,算法)