利用二叉树中序及先序遍历确定该二叉树的后序序列
1000(ms)
10000(kb)
2182 / 4615
已知二叉树的中序和先序遍历可以唯一确定后序遍历、已知中序和后序遍历可以唯一确定先序遍历,但已知先序和后序,却不一定能唯一确定中序遍历。现要求根据输入的中序遍历结果及先序遍历结果,要求输出其后序遍历结果。
输入
输入数据占2行,其中第一行表示中序遍历结果,第二行为先序遍历结果。
输出
对测试数据,输出后序遍历结果。
样例输入
BFDAEGC ABDFCEG
样例输出
FDBGECA
#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
typedef struct node
{
char data;
struct node *l,*r;
}Tree;
Tree* built(char *first,char *mid,int n)
{
char *p;
Tree *T;
int k=0;
if(n==0) return NULL;
T=(Tree *)malloc(sizeof(Tree));
T->data=*first;
for(p=mid;p<mid+n;p++)
{
if(*p==T->data) break;
k++;
}
T->l=built(first+1,mid,k);
T->r=built(first+1+k,mid+k+1,n-1-k);
return T;
}
void print(Tree *&l)
{
if(l)
{
print(l->l);
print(l->r);
cout<<l->data;
}
}
int main()
{
Tree *l;
char first[1000],mid[1000];
cin>>mid>>first;
l=built(first,mid,strlen(mid));
print(l);
return 0;
}