Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 14640 | Accepted: 9091 |
Description
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
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
Sample Input
DBACEGF ABCDEFG BCAD CBAD
Sample Output
ACBFGED
CDAB
已知二叉树的前序后序遍历求后序遍历。
代码:
注意in的范围的变化和pre一样
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; typedef struct Tree{ Tree *l, *r; char value; Tree(){ l = NULL; r = NULL; } }Tree; int find(char c, char *in){ for(int i = 0; in[i]; i++){ if(c == in[i]){ return i; } } } void make(int n, char *pre, char *in, Tree *&t){ if(n <= 0)return; int k = find(pre[0], in); t = new Tree(); t->value = pre[0]; make(k, pre + 1, in, t->l); make(n - 1 - k, pre + k + 1, in + k + 1, t->r); } void postVisit(Tree *tree){ if(tree->l) postVisit(tree->l); if(tree->r) postVisit(tree->r); printf("%c", tree->value); } int main(){ char pre[30],in[30]; while(~scanf("%s%s", pre, in)){ Tree t; make(strlen(pre), pre, in, t.l); postVisit(t.l); puts(""); } return 0; }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std; typedef struct Tree{ Tree *l, *r; char value; Tree(){ l = NULL; r = NULL; } }Tree; int find(char c, char *in){ for(int i = 0; in[i]; i++){ if(c == in[i]){ return i; } } } Tree* make(int n, char *pre, char *in){ if(n <= 0)return NULL; int k = find(pre[0], in); Tree *t = new Tree(); t->value = pre[0]; t->l = make(k, pre + 1, in); t->r = make(n - 1 - k, pre + k + 1, in + k + 1); return t; } void postVisit(Tree *tree){ if(tree->l) postVisit(tree->l); if(tree->r) postVisit(tree->r); printf("%c", tree->value); } int main(){ char pre[30],in[30]; while(~scanf("%s%s", pre, in)){ Tree *t; t = make(strlen(pre), pre, in); postVisit(t); puts(""); } return 0; }