您的位置:首页 > 其它

PKU2255 Tree Recovery 二叉树的遍历

2010-07-18 14:01 357 查看
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 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>
#define M 30
char stack[M];
int top;
void Create(char *pre,char *mid)
{
char ps1[M],ps2[M],*qs1,*qs2;
int index;
if(strlen(pre))
{
stack[top++]=pre[0];
index=strchr(mid,pre[0])-mid;
qs1=mid;qs2=mid+index+1;
mid[index]=0;
strncpy(ps1,pre+1,index);
ps1[index]=0;
strcpy(ps2,pre+index+1);
Create(ps2,qs2);
Create(ps1,qs1);
}
return ;
}
int main()
{
char pre[M],mid[M];
while(scanf("%s%s",pre,mid)!=-1)
{
top=0;
Create(pre,mid);
while(top>0)
printf("%c",stack[--top]);
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: