由树的先序遍历序列和中序遍历序列创建一棵二叉树。
输出二叉树的后序遍历序列。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElementType;
typedef struct BiTNode {
ElementType data;
struct BiTNode* lchild;
struct BiTNode* rchild;
}BiTNode, * BiTree;
BiTree CreatBinTree(char* pre, char* in, int n)
{
BiTree T;
int i;
if (n <= 0) return NULL;
T = (BiTree)malloc(sizeof(BiTNode));
T->data = pre[0];
for (i = 0; in[i] != pre[0]; i++);
//找到中序遍历中与先序遍历中第一个相同元素的位置
//中序中前i个是左子树,后i个是右子树
T->lchild = CreatBinTree(pre + 1, in, i);
//建立右子树,后i个是右子树,所以中序的后i个是右子树,先序的后i个是右子树
T->rchild = CreatBinTree(pre + i + 1, in + i + 1, n - i - 1);
return T;
}
void pr(BiTree T)
{
if (T)
{
pr(T->lchild);
pr(T->rchild);
printf("%c", T->data);
}
}
int main()
{
BiTree T;
char prelist[100];
char inlist[100];
int length;
printf("请输入前序遍历:");
scanf("%s", prelist);
printf("请输入中序遍历:");
scanf("%s", inlist);
length = strlen(prelist);
T = CreatBinTree(prelist, inlist, length);
printf("后序遍历的结果是:");
pr(T);
return 0;
}
测试数据:
先序遍历序列:ABDGCEF
中序遍历序列:DGBAECF