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