7-10 重建二叉树 (25 分)
给定一棵二叉树的前序遍历和中序遍历的结果,求其后序遍历。
输入格式:
输入可能有多组,以EOF结束。 每组输入包含两个字符串,分别为树的前序遍历和中序遍历。每个字符串中只包含字母和数字且互不重复。
输出格式:
对于每组输入,用一行来输出它后序遍历的结果。
输入样例:
ABDC BDAC
ABCD BADC
输出样例:
DBCA
BDCA
上代码:
#include <bits/stdc++.h>
using namespace std;
struct treeNode{
char Data;
struct treeNode *right;
struct treeNode *left;
};
typedef struct treeNode* Node;
Node createTree(char *X,char *Z,int temp){
Node root=(Node)malloc(sizeof(struct treeNode));
if(temp==0)return NULL;
root->left=NULL;
root->right=NULL;
root->Data=*X;
int k;
for(int i=0;i<temp;i++){
if(*X==*(Z+i))
{k=i;break;}
}
root->left=createTree(X+1,Z,k);
root->right=createTree(X+k+1,Z+k+1,temp-k-1);
return root;
}
void houxubianli(Node root)
{
if(root==NULL)return;
if(root->left!=NULL)
houxubianli(root->left);
if(root->right!=NULL)
houxubianli(root->right);
cout<<root->Data;
}
int main()
{
int N=1000;
char xx[N];
char zx[N];
while((scanf("%s",xx))!=EOF){
scanf("%s",zx);
int n=strlen(zx);
Node Root=createTree(xx,zx,n);
houxubianli(Root);
cout<<endl;
}
return 0;
}