问题 A: 复原二叉树
时间限制: 1 Sec 内存限制: 32 MB
提交: 102 解决: 76
题目描述
小明在做数据结构的作业,其中一题是给你一棵二叉树的前序遍历和中序遍历结果,要求你写出这棵二叉树的后序遍历结果。
输入
输入包含多组测试数据。每组输入包含两个字符串,分别表示二叉树的前序遍历和中序遍历结果。每个字符串由不重复的大写字母组成。
输出
对于每组输入,输出对应的二叉树的后续遍历结果。
样例输入
DBACEGF ABCDEFG BCAD CBAD
样例输出
ACBFGED CDAB
经验总结
这题。。很基础啦,没什么可以总结的~~看代码( 。ớ ₃ờ)ھ
正确代码
#include <cstdio>
const int maxn=200;
char pre[maxn],in[maxn];
struct node
{
char data;
node *lchild;
node *rchild;
};
void post(node * root)
{
if(root==NULL)
return;
post(root->lchild);
post(root->rchild);
printf("%c",root->data);
}
node * create(int preL,int preR,int inL,int inR)
{
if(preL>preR)
return NULL;
node * p=new node;
p->data=pre[preL];
int k;
for(k=inL;k<inR;++k)
if(in[k]==pre[preL])
break;
int numleft=k-inL;
p->lchild=create(preL+1,preL+numleft,inL,k-1);
p->rchild=create(preL+numleft+1,preR,k+1,inR);
return p;
}
int main()
{
int n;
while(~scanf("%s",pre))
{
scanf("%s",in);
n=0;
while(pre[n]!='\0')
n++;
node *root=create(0,n-1,0,n-1);
post(root);
printf("\n");
}
return 0;
}