若已知结点的先序序列和中序序列,能确定一颗二叉树
若已知结点的中序序列和后序序列,也能确定一颗二叉树
算法思想:
由先序序列和中序序列恢复二叉树的递归思想:
先根据先序序列第一个结点确定二叉树的根结点,然后在中序序列中查找到该元素,根据该元素在中序序列中的位置,确定根结点的左,右子树的中序序列,再在先序序列中确定左,右子树的先序序列,最后由左子树的先序序列与中序序列建立左子树,由右子树的先序序列与中序序列建立右子树。
根据二叉树的中序和后序序列恢复二叉树的递归思想是:
先根据后序序列的最后一个结点确立二叉树的根结点,根据该元素在中序序列中的位置,确定根结点的左,右子树的中序序列,再在后序序列中确定左,右子树的后序序列,最后由左子树的后序序列与中序序列建立左子树,由右子树的后序序列与中序序列建立右子树。
代码实现:
(1)由先序序列和中序序列恢复二叉树,并用后序输出
#include
#include
#define MAX 20
typedef struct Tree
{
char data;
Tree *Lchild, *Rchild;
}Tree, *BitTree;
void PreTree(char a[], char b[], int i, int j, int k, int h, BitTree *t)
{
int m;
(*t) = (BitTree)malloc(sizeof(Tree));
(*t)->data = a[i];
m = k;
while (b[m] != a[i])
m++;
if (m == k)
(*t)->Lchild = NULL;
else
PreTree(a, b, i + 1, i + m - k, k, m - 1, &((*t)->Lchild));
if (m == h)
(*t)->Rchild = NULL;
else
PreTree(a, b, i + m - k + 1, j, m + 1, h, &((*t)->Rchild));
}
void show(BitTree t) //以后序遍历输出二叉树
{
if (t)
{
show((t->Lchild));
show((t->Rchild));
printf("%2c", t->data);
}
}
int main()
{
BitTree t;
char a[MAX];
char b[MAX];
int i, j, n;
printf("输入结点个数");
scanf("%d", &n);
printf("请输入前序\n");
flushall();
for (i = 0; i < n; i++)
{
scanf("%c", &a[i]);
}
printf("请输入中序\n");
flushall();
for (j = 0; j < n; j++)
{
scanf("%c", &b[j]);
}
PreTree(a, b, 0, n - 1, 0, n - 1, &t);
printf("后序输出二叉树:\n");
show(t);
return 0;
}
(2)由中序序列和后序序列恢复二叉树,并用先序输出
#include
#include
#define MAX 20
typedef struct Tree
{
char data;
struct Tree *Lchild, *Rchild;
}Tree,*Bitree;
void Rebuit(char a[], char b[], int i, int j, int k, int h, Bitree *t)
{
int m;
m = i;
(*t) = (Bitree)malloc(sizeof(Tree));
(*t)->data = b[h];
while (a[m] != b[h])
{
m++;
}
if (m == i)
(*t)->Lchild = NULL;
else
Rebuit(a, b, i, m - 1, k, k + m - i - 1,&((*t)->Lchild));
if (m == j)
(*t)->Rchild = NULL;
else
Rebuit(a, b, m + 1, j, k + m - i, h - 1, &((*t)->Rchild));
}
void show(Bitree t)
{
if (t)
{
printf("%2c", t->data);
show(t->Lchild);
show(t->Rchild);
}
}
int main()
{
Bitree t;
int n;
char a[MAX], b[MAX];
printf("请输入结点个数\n");
scanf("%d", &n);
printf("请输入中序序列\n");
int i, j;
flushall();
for (i = 0; i < n; i++)
{
scanf("%c", &a[i]);
}
printf("请输入后序序列\n");
flushall();
for (j = 0; j < n; j++)
{
scanf("%c", &b[j]);
}
Rebuit(a, b, 0, n - 1, 0, n - 1, &t);
printf("恢复成功!\n前序序列输出为:\n");
show(t);
return 0;
}