欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POJ2255(Tree Recovery)二叉树的重建

程序员文章站 2022-05-19 19:59:46
...

题目来源:
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
题意描述:
给出一棵树的前序和中序让你写出所给书的后序;
解题思路:
采用递归的方法,先找到根结点,然后递归出左子树和右子树,主要的还是明白递归的过程,实际上每一次都是找下一个根节点,如(在找到根结点后需要找到左边子树的根节点而前序的下一个结点就是下一个根节点,之后重复以亲、前的找根结点再找所在位置就行

build(temp,s1+1,s2,s);
build(len-temp-1,s1+temp+1,s2+temp+1,s+temp);
s[n-1]=s1[0]//这就是刚到的前序对应的下一个结点就
            //是下一个根节点所以每一次都是靠这一步将节点归位 

Accept Code:

#include <stdio.h>
#include <string.h> 
char s[200],p[200],str[2000];
void build(int len,char *s, char *p, char *str)
{
	if(len<=0) return ;
	int temp;
	for(int i=0; i<len; i++)
	{
		if(p[i]==s[0])
		{
		  temp=i; break;
		}
	}
	build(temp,s+1,p,str);
	build(len-temp-1,s+temp+1,p+temp+1,str+temp);
	str[len-1]=s[0];
}
int main()
{
	int i,j,k,n,m;
	while(scanf("%s%s", s,p)==2)
	{
		int len=strlen(s);
		build(len,s,p,str);
		str[len]='\0';
		printf("%s\n", str);
	}
	return 0;
 } 
相关标签: 练习赛