根据前序和中序唯一生成一颗二叉树

/**
*2018.10.17 18:06
*根据前序和中序唯一生成一颗二叉树
*/
#include<stdio.h>

#define MAX 100

typedef char Elem;

typedef struct BTNode{
	Elem data;
	struct BTNode *lchild;
	struct BTNode *rchild;
}BTNode;


BTNode* createBT(Elem pre[], int ps, int pt, Elem mid[], int ms, int mt);
void preOrder(BTNode *t);
void midOrder(BTNode *t);
void beOrder(BTNode *t);

int main(void) {
	
	Elem pre[] = {'A','B','D' ,'E' ,'C' ,'F' ,'G'};
	Elem mid[] = {'D','B','E' ,'A' ,'F' ,'C' ,'G'};
	BTNode *T = createBT(pre, 0, 6, mid, 0, 6);

	puts("前序:");
	preOrder(T); putchar('\n');
	puts("中序:");
	midOrder(T); putchar('\n');
	puts("后序:");
	beOrder(T);

	putchar('\n');
	system("pause");
	return 0;
}

BTNode* createBT(Elem pre[], int ps, int pt, Elem mid[], int ms, int mt) {

	if (ps > pt)
		return NULL;

	int j = ms;

	BTNode *node = (BTNode *)malloc(sizeof(BTNode));
	node->lchild = NULL;
	node->rchild = NULL;

	while (j <= mt && pre[ps] != mid[j]) ++j;

	node->data = pre[ps];

	node->lchild = createBT(pre, ps + 1, ps + j - ms, mid, ms, j - 1);
	node->rchild = createBT(pre, ps + j - ms + 1, pt, mid, j + 1, mt);

		return node;
}

void preOrder(BTNode *t) {
	if (t != NULL) {
		printf("%c  ", t->data);
		preOrder(t->lchild);
		preOrder(t->rchild);
	}
}

void midOrder(BTNode *t) {
	if (t != NULL) {
		midOrder(t->lchild);
		printf("%c  ", t->data);
		midOrder(t->rchild);
	}
}

void beOrder(BTNode *t) {
	if (t != NULL) {
		beOrder(t->lchild);
		beOrder(t->rchild);
		printf("%c  ", t->data);
	}
}
发布了48 篇原创文章 · 获赞 3 · 访问量 5139

猜你喜欢

转载自blog.csdn.net/ydeway/article/details/101039730
今日推荐