Tree Recovery(由先、中序列构建二叉树)

时间:2021-08-17 13:24:15

题目来源:

http://poj.org/problem?id=2255

题目描述:

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

解题思路:
根据给出的先根序列和中根序列构建二叉树后,后序遍历二叉树即可。
拿第一个样例来说,现在先根序列中找到根节点D,然后在中根序列中找到D,可以得到以D为根节点的二叉树的左子树有ABC,以D为根节点的二叉树的右子树有EFG。接下来在先根序列中找到B,再在中根序列中将以B为根节点的二叉树
的左右子树找到,如此递归,直至将序列处理完毕。
代码实现:
 #include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char ch;
struct node *left,*right;
};
struct node* creat(char *pre,char *in,int len);
void post(struct node* head);
int main()
{
char pre[],in[];
struct node *head;
head = ( struct node *)malloc(sizeof(struct node));
while(scanf("%s %s",pre,in) != EOF)
{
int len=strlen(pre);
head=creat(pre,in,len); post(head);//后序遍历
printf("\n");
}
return ;
}
struct node* creat(char *pre,char *in,int len)
{
if(len==)
return NULL; struct node *head;
head = (struct node*)malloc(sizeof(struct node));
head->ch=pre[]; char *p;
for(p=in;p != NULL;p++)//指针字符串中空为结束标志
if(*p == *pre)
break; int k=p-in;
head->left=creat(pre+,in,k);
head->right=creat(pre+k+,p+,len-k-);
return head;
}
void post(struct node* head)
{
if(head == NULL)
return;
post(head->left);
post(head->right);
printf("%c",head->ch);
}

易错分析:

注意注释,指针字符串和字符串数组还是有一定区别的,比如结束标志位NULL