POJ2255(Tree Recovery)二叉树的重建
题目来源:
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;
}
推荐阅读
-
1086 Tree Traversals Again (25 分)(二叉树的遍历)
-
Python利用前序和中序遍历结果重建二叉树的方法
-
Python实现重建二叉树的三种方法详解
-
[PHP] 算法-根据前序和中序遍历结果重建二叉树的PHP实现
-
剑指 Offer 07. 重建二叉树——【前中序】和【中后序】重建二叉树的递归思路详解
-
21天刷题计划之17.1—maximum-depth-of-binary-tree(二叉树的最大深度)(Java语言描述)
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
leetcode 235. Lowest Common Ancestor of a Binary Search Tree(二叉树的最低共同祖先)
-
tree traversal (树的遍历) - 中序遍历 (inorder traversal) - 二叉树的中序遍历
-
tree traversal (树的遍历) - 前序遍历 (preorder traversal) - 二叉树的前序遍历