遍历序列恢复二叉树

若已知结点的先序序列和中序序列,能确定一颗二叉树

若已知结点的中序序列和后序序列,也能确定一颗二叉树

算法思想:

由先序序列和中序序列恢复二叉树的递归思想:

先根据先序序列第一个结点确定二叉树的根结点,然后在中序序列中查找到该元素,根据该元素在中序序列中的位置,确定根结点的左,右子树的中序序列,再在先序序列中确定左,右子树的先序序列,最后由左子树的先序序列与中序序列建立左子树,由右子树的先序序列与中序序列建立右子树。

根据二叉树的中序和后序序列恢复二叉树的递归思想是:

先根据后序序列的最后一个结点确立二叉树的根结点,根据该元素在中序序列中的位置,确定根结点的左,右子树的中序序列,再在后序序列中确定左,右子树的后序序列,最后由左子树的后序序列与中序序列建立左子树,由右子树的后序序列与中序序列建立右子树。


代码实现:

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




  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值