二叉树重建(根据后序中序重建二叉树)


1:根据二叉树的后续序列和中序序列可以确定唯一的二叉树;

2:二叉树遍历顺序   

   前序遍历;根节点-->左子树-->右子树;

   中序遍历:左子树-->根节点-->右子树;

   后序遍历:左子树-->右子树-->根节点;

下面重建二叉树之后再层序遍历

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int post[31],in[31];

int m,ele_sum;
typedef struct trees
{
	int num;
	struct trees *lchild,*rchild;
}Tree;

Tree *q[31];
Tree *b[31];
Tree *creat(int lend,int rend,Tree *root)
{
	int po,i;
	Tree *p,*q;

	if(ele_sum==0||abs(lend-rend)<=1)
		return root=NULL;

	for(i=1;i<=m;i++)
	{
		if(in[i]==post[ele_sum])
		{
			po=i;
			break;
		}
	}

	if(po>lend&&po<rend)
	{
		p=(Tree*)malloc(sizeof(Tree));
		p->num=post[ele_sum];
		p->lchild=p->rchild=NULL;
		root=p;

		ele_sum--;
		root->rchild=creat(po,rend,root->rchild);
		root->lchild=creat(lend,po,root->lchild);
	}
	else root=NULL;

	return root;
}

void level(Tree *root,int m)
{
	int i=0,k=0;
	if(root)
	{
		b[i]=root;
		while(b[i]->lchild && b[i]->rchild)
		{
			if(b[i]->lchild)
			{
				k++;
				b[k]=b[i]->lchild;
			}
			if(b[i]->rchild)
			{
				k++;
				b[k]=b[i]->rchild;
			}
			i++;
		}
		for(i=0;i<m;i++)
			printf("%d ",b[i]->num);
	}
}

int main()
{
	int po,i;
	int lend,rend;
	Tree *p,*head;
	while(scanf("%d",&m)!=EOF)
	{
		head=NULL;
		lend=0;
		rend=m+1;
		ele_sum=m;

		for(i=1;i<=m;i++)
			scanf("%d",&post[i]);
		for(i=1;i<=m;i++)
			scanf("%d",&in[i]);

		for(i=1;i<=m;i++)
		{
			if(in[i]==post[ele_sum])
			{
				po=i;
				break;
			}
		}

		p=(Tree*)malloc(sizeof(Tree));
		p->num=post[ele_sum];
		p->lchild=p->rchild=NULL;
		head=p;

		ele_sum--;
		head->rchild=creat(po,rend,head->rchild);
		head->lchild=creat(lend,po,head->lchild);

		level(head,m);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值