题目链接:http://codeup.cn/problem.php?cid=100000611&pid=0
题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
代码
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
struct node {
char data;
node* lchild;
node* rchild;
};
string pre, in;
node* create(int prel, int prer, int inl, int inr) {
if(prel > prer)
return NULL;
node* root = new node;
root->data = pre[prel];
int k;
for(k = inl; k <= inr; k++)
if(in[k] == pre[prel])
break;
int numl = k - inl;
root->lchild = create(prel + 1, prel + numl, inl, k - 1);
root->rchild = create(prel + numl + 1, prer, k + 1, inr);
return root;
}
void postorder(node* root) {
if(root == NULL)
return;
postorder(root->lchild);
postorder(root->rchild);
cout<<root->data;
}
int main() {
while(cin>>pre) {
cin>>in;
node* root = create(0, pre.size() - 1, 0, in.size() - 1);
postorder(root);
cout<<endl;
}
return 0;
}