标签:
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 is terminated by end of file.
DBACEGF ABCDEFG BCAD CBAD
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[n] == 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; }
标签:
原文地址:http://www.cnblogs.com/hfc-xx/p/4671835.html