Little Valentine liked playing with binary trees very much. Her favorite game was constructing randomly looking binary trees with capital letters in the nodes.
This is an example of one of her creations:
D / \ / \ B E / \ \ / \ \ A C G / / F
To record her trees for future generations, she wrote down two strings for each tree: a preorder traversal (root, left subtree, right subtree) and an inorder traversal (left subtree, root, right subtree). For the tree drawn above the preorder traversal is DBACEGF and the inorder traversal is ABCDEFG.
She thought that such a pair of strings would give enough information to reconstruct the tree later (but she never tried it).
Now, years later, looking again at the strings, she realized that reconstructing the trees was indeed possible, but only because she never had used the same letter twice in the same tree.
However, doing the reconstruction by hand, soon turned out to be tedious.
So now she asks you to write a program that does the job for her!
Input
The input will contain one or more test cases.
Each test case consists of one line containing two strings preord and inord, representing the preorder traversal and inorder traversal of a binary tree. Both strings consist of unique capital letters. (Thus they are not longer than 26 characters.)
Input is terminated by end of file.
Output
For each test case, recover Valentine's binary tree and print one line containing the tree's postorder traversal (left subtree, right subtree, root).
Sample Input
DBACEGF ABCDEFG BCAD CBAD
Sample Output
ACBFGED CDAB
题意:
给出一棵二叉树的前序遍历与中序遍历,求后序遍历.
其中二叉树由不重复的大写字母组成,每个节点一个字母.
思路:
这道题我觉得是用递归,因为先序遍历是先根,后左子树,最后右子树,而中序遍历则是先左子树,
再根,最后右子树,所以我们可以递归处理,先序遍历的第一个元素是父节点,找到在中序遍历的这个点
的位置,将中序序列分成两部分,对非空的子树进行递归
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char s1[27],s2[27],s3[27];//s1是树的前序遍历,s2是树的中序遍历
int k;
void fun(int l1,int t1,int l2,int t2)
{
if(l1>t1)//中止条件
return;
//找到根节点
int a=0;
while(s2[l2+a]!=s1[l1])
a++;
fun(l1+1,l1+a,l2,l2+a-1);//左子树
fun(l1+a+1,t1,l2+a+1,t2);//右子树
s3[k++]=s1[l1];
}
int main()
{
while(~scanf("%s%s",s1,s2))
{
int l=strlen(s1);
k=0;
fun(0,l-1,0,l-1);
s3[l]='\0';
printf("%s\n",s3);
}
return 0;
}