代码如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElemType;
typedef struct BiTNode {
ElemType data;
struct BiTNode* lchild;
struct BiTNode* rchile;
}BiTNode,*BiTree;
//先序遍历
void preOrder(BiTree T) {
if (T != NULL) {
printf("%c ", T->data);
preOrder(T->lchild);
preOrder(T->rchile);
}
}
//中序遍历
void inOrder(BiTree T) {
if (T != NULL) {
inOrder(T->lchild);
printf("%c ", T->data);
inOrder(T->rchile);
}
}
//后续遍历
void postOrder(BiTree T) {
if (T != NULL) {
postOrder(T->lchild);
postOrder(T->rchile);
printf("%c ", T->data);
}
}
BiTNode* creatBiTree(char* preOrderArra, int preFirstIndex, int preLastIndex, char* inOrderArra, int inFirstIndex, int inLastIndex) {
//如果起始位置大于结束位置,说明子树为空
if (preFirstIndex > preLastIndex) {
return NULL;
}
BiTNode* pnode = (BiTNode*)malloc(sizeof(BiTNode));
pnode->data = preOrderArra[preFirstIndex];
int index;
for (index = inFirstIndex; index <= inLastIndex; index++) {
if (inOrderArra[index] == pnode->data) {
break;
}
}
pnode->lchild = creatBiTree(preOrderArra, preFirstIndex + 1, preFirstIndex + index - inFirstIndex, inOrderArra, inFirstIndex, index - 1);
pnode->rchile = creatBiTree(preOrderArra, preFirstIndex + index - inFirstIndex+1, preLastIndex, inOrderArra, index+1, inLastIndex);
return pnode;
}
int main()
{
char preOrderArra[50], inOrderArra[50];
gets_s(preOrderArra);
gets_s(inOrderArra);
int preOrderArralength = strlen(preOrderArra);
int inOrderArralength = strlen(inOrderArra);
BiTree T = creatBiTree(preOrderArra, 0, preOrderArralength - 1, inOrderArra, 0, inOrderArralength - 1);
preOrder(T);//先序遍历
printf("\n");
inOrder(T);//中序遍历
printf("\n");
postOrder(T);//后序遍历
printf("\n");
return 0;
}