二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问根,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
题目:给定一棵二叉树的前序和中序遍历,求其后续遍历。
样例输入:
ABC
BAC
FDXEAG
XDEFAG
样例输出:
B C A
X E D G A F
#include<stdio.h>
#include<string.h>
struct Node { //树结点结构体
Node *lchild;
Node *rchild;
char c;
}Tree[50];
int loc; //静态数组中已分配的结点个数
Node *creat() { //申请一个结点空间,返回指向其的指针
Tree[loc].lchild == NULL;
Tree[loc].rchild == NULL;
return &Tree[loc++];
}
char str1[30], str2[30];
void postOrder(Node *T) { //后序遍历
if (T->lchild != NULL)
postOrder(T->lchild);
if (T->rchild != NULL)
postOrder(T->rchild);
printf("%c", T->c);
}
Node *build(int s1, int e1, int s2, int e2) {
//由字符串的前序和中序遍历还原树,并返回其根节点
Node *ret = creat();
ret->c = str1[s1]; //该结点为前序遍历中的第一个结点
int rootIdx;
for (int i = s2; i <= e2; i++) {
if (str2[i] == str1[s1]) {
rootIdx = i;
break;
}
}
if (rootIdx != s2) { //若左子树不为空
ret->lchild = build(s1 + 1, s1 + (rootIdx - s2), s2, rootIdx - 1);
//递归还原其左子树
}
if (rootIdx != e2) { //若右子树不为空
ret->rchild = build(s1 + (rootIdx - s2) + 1, e1, rootIdx + 1, e2);
} //递归还原其右子树
return ret;
}
int main() {
while (scanf("%s", str1)!=EOF) {
scanf("%s", str2);
loc = 0;
int L1 = strlen(str1);
int L2 = strlen(str2);
Node *T = build(0, L1 - 1, 0 ,L2 - 1);//还原整棵树,其根节点保存在T中
postOrder(T);
printf("\n");
}
return 0;
}