您的位置:首页 > 其它

POJ 2255 Tree Recovery(还原树)

2015-12-23 20:01 507 查看
题目链接:POJ 2255

题意:

给出二叉树的前序和中序遍历求出后序遍历。

分析:

递归。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;

struct TreeNode {
	struct TreeNode* left;
	struct TreeNode* right;
	char elem;
};

void BinaryTreeFromOrderings(char* inorder, char* preorder, int length)
{
	if (length == 0) return;
	TreeNode* node = new TreeNode;
	node->elem = *preorder;
	int rootIndex = 0;
	for (;rootIndex < length;rootIndex++)
		if (inorder[rootIndex] == *preorder) break;
	BinaryTreeFromOrderings(inorder, preorder + 1, rootIndex);
	BinaryTreeFromOrderings(inorder + rootIndex + 1, preorder + rootIndex + 1, length - (rootIndex + 1));
	cout << node->elem;
	return;
}
int main()
{

#ifdef LOCAL
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
#endif
	char in[27], pre[27];
	int len;
	while (cin >> pre >> in)
	{
		len = strlen(pre);
		BinaryTreeFromOrderings(in, pre, len);
		cout << endl;
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: