-
题目描述:
-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
-
输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
-
输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
-
ABC BAC FDXEAG XDEFAG
-
BCA XEDGAF
样例输入:
-
样例输出:
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
struct node
{
node* lchild;
node* rchild;
char c;//结点字符信息
};
node tree[100];
int loc = 0;
string str1, str2;//保存前序和中序遍历结果字符串
node* create()
{
tree[loc].lchild = tree[loc].rchild=NULL;
return &tree[loc++];//返回指针,且loc相加
}
//由字符串的前序遍历和中序遍历还原树,并返回其根结点,其中前序遍历的结果为str[s1]到str1[e1],中序遍历的结果为str[s2]到str[e2];
node* build(int s1, int e1, int s2, int e2)
{
node *ret = create();//为该树根结点申请空间
ret->c = str1[s1];
int rootinx(0);
for (int i = s2; i <= e2; i++)
{
if (str1[s1] == str2[i])
{
rootinx = i;
break;
}
}
if (rootinx != s2)//左子树非空
{
ret->lchild = build(s1 + 1, s1 + rootinx - s2, s2, rootinx - 1);
}
if (rootinx != e2)
{
ret->rchild = build(s1 + rootinx - s2 + 1, e1, rootinx + 1, e2);
}
return ret;
}
void postOrder(node* T)//后序遍历
{
if (T->lchild != NULL)
{
postOrder(T->lchild);
}
if (T->rchild != NULL)
{
postOrder(T->rchild);
}
cout << T->c;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("D:\\in.txt", "r", stdin);
freopen("D:\\out.txt", "w", stdout);
#endif
while (cin >> str1)
{
cin >> str2;
loc = 0;
int l1 = str1.size();
int l2 = str2.size();
node* T = build(0, l1 - 1, 0, l2 - 1);//建树
postOrder(T);//后序遍历
cout << endl;
}
return 0;
}