Description

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 file 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

题意:

      给你先序遍历和中序遍历,求后序遍历。

思路:

第一步,根据前序遍历,根结点为D

第二步,观察中序遍历ABCDEFG。其中root节点D左侧的ABC必然是root的左子树,D右侧的EFG必然是root的右子树。

第三步,观察左子树ABC,左子树的中的根节点必然是树的root的leftchild。在前序遍历中,树的root的leftchild位于root之后,所以左子树的根节点为B。

第四步,同理,root的右子树节点EFG中的根节点也可以通过前序遍历求得。在前序遍历中,一定是先把root和root的所有左子树节点遍历完之后才会遍历右子树,并且遍历的左子树的第一个节点就是左子树的根节点。同理,遍历的右子树的第一个节点就是右子树的根节点。

第五步,观察发现,上面的过程是递归的。先找到当前树的根节点,然后划分为左子树,右子树,然后进入左子树重复上面的过程,然后进入右子树重复上面的过程。最后就可以还原一棵树了。

1. 确定根,确定左子树,确定右子树

2. 在左子树中递归

3. 在右子树中递归

4 .打印当前根

代码:

#include<stdio.h>
#include<string.h>
char s1[30],s2[30];
int j;
void find(int begin,int end)
{
	int i;
	if(begin>end)
		return;
	for(i=0;i<end;i++)
	{
		if(s1[j]==s2[i])   //找根节点
			break;
	}
	j++;
	find(begin,i-1);//左子树
	find(i+1,end);//右子树
	printf("%c",s2[i]);
}
int main()
{
	int len;
	while(scanf("%s%s",s1,s2)!=EOF)
	{
		j=0;
		len=strlen(s2);
		find(0,len-1);
		printf("\n");
	}
	return 0;
 }