POJ2255 Tree Recovery(C++_树的遍历)
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
Process
通过前序遍历和中序遍历求后序遍历,二叉树这块就是这样,前序和后序知道其中一个,中序遍历要是也知道的话就可以知道二叉树的形状,其实很好理解;
打个比方:
知道前序遍历你就知道前序遍历的第一个一定是根对吧,再去中序遍历中找根,找到之后会发现,根把中序遍历分成了两半,再根据分成的两半把前序遍历除去根的部分也切成两半就好了,后面一直重复操作,直到最后一个节点。(后序+中序也是这个道理)。
Code
#include<iostream>
#include<vector>
#include<string>
using namespace std;
string a, b;
vector<char> str;
void tree(int l1, int r1, int l2, int r2)
{
int t = 0;
if (l1 > r1)
return;
while (a[l1] != b[l2 + t])t++;
tree(l1 + 1, l1 + t, l2, l2 + t - 1);
tree(l1 + t + 1, r1, l2 + t + 1, r2);
str.push_back(a[l1]);
}
int main()
{
while (cin >> a >> b)
{
str.clear();
tree(0, a.size() - 1, 0, b.size() - 1);
for (int i = 0; i < str.size(); i++)
cout << str[i];
cout<<endl;
}
return 0;
}
上一篇: eBay开源新数据库技术Kylin,支持TB到PB级数据量
下一篇: 0-1字典树总结和经典例题
推荐阅读
-
1086 Tree Traversals Again (25 分)(二叉树的遍历)
-
tree traversal (树的遍历) - 中序遍历 (inorder traversal) - 二叉树的中序遍历
-
tree traversal (树的遍历) - 前序遍历 (preorder traversal) - 二叉树的前序遍历
-
tree traversal (树的遍历) - 前序遍历 (preorder traversal) - 对称二叉树
-
【蓝桥杯_真题演练】第十届C/C++省赛B组_G- 完全二叉树的权值(C++_树_遍历)
-
Tree Traversal(二叉树的遍历)
-
数据结构-树与二叉树-二叉树的递归遍历(Tree UVA - 548||Not so Mobile UVA - 839||The Falling Leaves UVA - 699)
-
数据结构与算法1:二叉树(binary_tree)的前、中、后序(深度优先)和广度优先遍历及python代码实现
-
1086 Tree Traversals Again (25 分)(二叉树的遍历)
-
POJ2255(Tree Recovery)二叉树的重建