1. 程式人生 > >先序、中序、後序序列的二叉樹構造演算法

先序、中序、後序序列的二叉樹構造演算法

#include <iostream>
#include <queue>
using namespace std;

typedef char ElemType;

typedef struct BTNode
{
	ElemType data;
	BTNode *left, *right;
}BTNode;

void LevelOrder(BTNode* root)
{
	queue<BTNode*> q;
	if (root)
	{
		q.push(root);
		while (!q.empty())
		{
			BTNode* t = q.front();
			cout << t->data << ", ";
			if (t->left) q.push(t->left);
			if (t->right) q.push(t->right);
			q.pop();
		}
	}
	cout << endl;
}

BTNode* CreateBTByPreAndIn(ElemType* pre, ElemType* in, int n)
{
	if (n <= 0) return NULL;
	BTNode* b = new BTNode;
	b->data = *pre;
	int k;
	for (ElemType* p = in; p < in + n; p++)
	{
		if (*p == *pre)
		{
			k = p - in;
			break;
		}
	}
	b->left = CreateBTByPreAndIn(pre + 1, in, k);
	b->right = CreateBTByPreAndIn(pre + 1 + k, in + 1 + k, n - k - 1);
	return b;
}

BTNode* CreateBTByPostAndIn(ElemType* post, ElemType* in, int n)
{
	if (n <= 0) return NULL;
	BTNode* b = new BTNode;
	b->data = *(post + n - 1);
	int k;
	for (ElemType* p = in; p < in + n; p++)
	{
		if (*p == *(post + n - 1))
		{
			k = p - in;
			break;
		}
	}
	b->left = CreateBTByPostAndIn(post, in, k);
	b->right = CreateBTByPostAndIn(post + k, in + k + 1, n - k - 1);
	return b;
}

int main()
{

	const char* pre = "ABDGCEF";
	const char* in = "DGBAECF";
	const char* post = "GDBEFCA";
	LevelOrder(CreateBTByPreAndIn(const_cast<ElemType*>(pre), 
		const_cast<ElemType*>(in), strlen(pre)));
	LevelOrder(CreateBTByPostAndIn(const_cast<ElemType*>(post),
		const_cast<ElemType*>(in), strlen(post)));
	system("pause");
	return 0;
}