题目链接: POJ 2455
Describe: |
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:
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 |
题目大意:
给一棵二叉树的前序遍历和中序遍历,输出它的后序遍历。
解题思路:
前序遍历结果的头个节点就是二叉树的根节点,根据这个根节点将中序遍历分为两段,递归的去搜索左子树和右子树,最后打印根节点。
AC代码:
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 char pre[30],in[30]; // 存放前序遍历,中序遍历 6 void work(int l, int r, int ll, int rr) 7 { 8 if(l > r) return; 9 if(ll > rr) return; //左序号已经大于右序号时,返回 10 int tmp = ll; 11 while(in[tmp] != pre[l]) tmp++; // 找到根节点在中序遍历中的位置 12 work(l+1, l+tmp-ll, ll, tmp-1); // 找左子树 13 work(l+tmp-ll+1, r, tmp+1, rr); // 找右子树 14 cout << pre[l]; 15 } 16 int main() 17 { 18 while(~scanf("%s%s",pre,in)) 19 { 20 int len = strlen(pre); // 计算树的节点个数 21 work(0,len-1,0,len-1); 22 cout << endl; 23 } 24 return 0; 25 }