poj2255 (二叉树遍历)
2015-07-23 21:26
323 查看
poj2255
二叉树遍历
Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %lluDescription
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; }
相关文章推荐
- 编译修改过的felix失败记录
- 009语音识别-华为机试题目
- crossApp初级-开发环境-1
- Quartz2D复习(一)--- 基础知识 / 绘制线段圆弧 / 图片水印 / 截图
- ZABBIX企业监控实践(2):升级与配置Apache
- #1077 : RMQ问题再临-线段树
- 股票学习(K线分析)
- CODEVS1033
- Codeforces Gym 100513G G. FacePalm Accounting
- linux运维学习方法
- POJ 1222-EXTENDED LIGHTS OUT(高斯消元求解异或方程组)
- C语言(1)--解一元二次方程、将整数第五位清零、说谎、放鞭炮
- 7,鼠标学习四-滚轮
- C++Primer(第五版) 习题答案
- dwz分页组件中,一个奇怪的翻页问题的解决
- 2015第30周四Java日志组件
- 如何查看是否被肉鸡
- 计蒜客---加一
- [POJ3897] Maze Stretching (二分)(A*)
- Java练习题(一)