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

聽聞__發表於2018-04-19

1、定義

        如果同時知道二叉樹的先序序列和中序序列,或者同時知道二叉樹的後序序列和中序序列,就能確定這顆二叉樹的形狀。

2、應用

        通過二叉樹的先序序列、中序序列或後序序列、中序序列,可構造出唯一的二叉樹結構。

3、實現

(1)二叉樹的型別定義

typedef char ElemType;

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

(2)利用先序序列和中序序列構造二叉樹

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;
}

(4)利用後序序列和中序序列構造二叉樹

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;
}
4、測試
#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;
}



相關文章