您的位置:首页 > 其它

二叉树——中序、后序遍历得先序遍历

2015-12-23 20:12 267 查看
#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* aftorder, int length)
{
	if (length == 0) return;
	TreeNode* node = new TreeNode;
	node->elem = *(aftorder+length-1);
	cout << node->elem;
	int rootIndex = 0;
	for (;rootIndex < length;rootIndex++)
		if (inorder[rootIndex] == *(aftorder + length - 1)) break;
	BinaryTreeFromOrderings(inorder, aftorder, rootIndex);
	BinaryTreeFromOrderings(inorder + rootIndex + 1, aftorder + rootIndex, length - (rootIndex + 1));
	return;
}
int main()
{
	char *aft = "AEFDHZMG";
	char *in = "ADEFGHMZ";
	BinaryTreeFromOrderings(in, aft, 8);
	cout << endl;
	//Result is:GDAFEMHZ
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: