欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POJ2255 Tree Recovery(C++_树的遍历)

程序员文章站 2022-05-19 19:50:40
...

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;
}
相关标签: 简单树型结构