您的位置:首页 > 其它

poj2255 (二叉树遍历)

2015-07-23 21:26 323 查看

poj2255

二叉树遍历

Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu

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 Specification

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 Specification

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

题解:

提示:二叉树遍历而已。。。给出前序和中序,求后序

思路:

1、前序遍历的第一个字母是根

2、在中序遍历的字母串中找出 根字母,那么根字母左右两边的就分别是它的左、右子树

3、利用递归复原二叉树(把子树看作新的二叉树)

4、后序遍历特征:后序遍历字母串 自右至左

5、输出后序遍历时,只需按4的顺序从左到右排列,再倒置输出即可

看了一晚上二叉树,指针什么的真的不会,偶然发现了一个好东西,用的数组,精简了半天。很容易懂

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char mid[27];
char pre[27];
int n = -1;

void juge(int i, int j)
{
int k;
if(i > j) return;
n++;
for(k = i; k <= j; k++)
{
if(pre
== mid[k])
break;
}
juge(i, k - 1);//递归复原二元树
juge(k + 1, j);
printf("%c", mid[k]);

}
int main()
{
while(scanf("%s%s", pre, mid) == 2)
{
juge(0, strlen(pre) - 1);//用的漂亮
printf("\n");
n = -1;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: