给定一棵二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
长度为N的不包含重复英文字母(区别大小写)的字符串
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
FHIGDEBCA
根据还原二叉树那个题自己改的。。。
#include<bits/stdc++.h>
using namespace std;
struct Node
{
char data;
Node* lchild;
Node* rchild;
};
typedef struct Node* BTree;
BTree buildTree(char a[],char b[],int n){
BTree t=(BTree)malloc(sizeof(Node));
int i;
if(n==0)return NULL;
for(i=0;i<n;i++){
if(b[i]==a[0]){
break;
}
}
t->lchild= buildTree(a+1,b,i);
t->rchild=buildTree(a+i+1,b+i+1,n-i-1);
t->data=a[0];
return t;
}
void printTree(BTree root){
if(root){
if(root->lchild)printTree(root->lchild);
if(root->rchild)printTree(root->rchild);
cout<<root->data;
}
}
int main()
{
char a[101];
char b[101];
int n;
cin>>n;
cin>>a>>b;
BTree root=buildTree(a,b,n);
printTree(root);
}